2013-08-29 56 views
1

工作更上FP in Scala的例子,我试图实现Option特征的map功能如下:实现地图

sealed trait MyOption[+A] { 
    def map[B](f: A => B): Option[B] = this match { 
     case Some(a) => Some(f(a)) 
     case _ => None 
    } 
} 

然而,编译时错误显示,如果我理解正确的话,我不是在Some(A)的情况下,模式匹配正确。使用模式匹配,我如何编写第一个案例来获得一些(A)值匹配?

>scalac MyOption.scala 
MyOption.scala:3: error: constructor cannot be instantiated to expected type; 
found : Some[A(in class Some)] 
required: MyOption[A(in trait MyOption)] 
       case Some(a) => Some(f(a)) 
        ^
MyOption.scala:3: error: not found: value a 
       case Some(a) => Some(f(a)) 
            ^
two errors found 
+2

您正在混合Option和MyOption,MyOption#map的返回类型应该是MyOption,而不是Option。你确定你正在使用的是MyOption而不是Option? – stew

回答

4

您试图在其中斯卡拉提供的期权特征的子类,而不是你自己的特点的子类方面的一些术语和无定义地图。尝试类似于:

sealed trait MyOption[+A] { 
    import MyOption._ 
    def map[B](f: A => B): MyOption[B] = this match { 
     case MySome(a) => MySome(f(a)) 
     case _ => MyNone 
    } 
} 

object MyOption { 
    case class MySome[+A](a: A) extends MyOption[A] 
    case object MyNone extends MyOption[Nothing] 
}