在 Scala 示例中更多地研究FP,我尝试按如下方式实现Option
trait 的功能: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)
. 使用模式匹配,我如何编写第一个案例来获得 Some(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