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
您正在混合Option和MyOption,MyOption#map的返回类型应该是MyOption,而不是Option。你确定你正在使用的是MyOption而不是Option? – stew