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