Scala 子类模式匹配
Scala subclass pattern match
我正在尝试 运行 本书 "Functional Programming in Scala" 中的代码,它似乎是为旧版本的 scala(从 here 下载)编写的。 tmp.scala:
sealed trait Option[+A]
case class Some[+A](get: A) extends Option[A]
case object None extends Option[Nothing]
trait Option[+A] {
/* returns None if None, or function applied to the some object */
def map[B](f: A => B): Option[B] = this match {
case None => None
case Some(a) => Some(f(a))
}
}
抛出的错误是:
$ scala
Welcome to Scala 2.12.0-20161021-070700-8684ae8 (OpenJDK 64-Bit Server VM, Java 1.8.0_112).
scala> :load tmp.scala
tmp.scala:17: error: pattern type is incompatible with expected type;
found : None.type
required: Option[A]
case None => None
^
tmp.scala:17: error: type mismatch;
found : None.type
required: Option[B]
case None => None
^
tmp.scala:18: error: constructor cannot be instantiated to expected type;
found : Some[A(in class Some)]
required: Option[A(in trait Option)]
case Some(a) => Some(f(a))
^
tmp.scala:18: error: type mismatch;
found : Some[B]
required: Option[B]
case Some(a) => Some(f(a))
^
我尝试了各种codefu,但无济于事,似乎由于过时的语法而无法正确检测子类?
使用粘贴内容的 :paste file.scala
,而不是解释每一行的 :load file.scala
。
我正在尝试 运行 本书 "Functional Programming in Scala" 中的代码,它似乎是为旧版本的 scala(从 here 下载)编写的。 tmp.scala:
sealed trait Option[+A]
case class Some[+A](get: A) extends Option[A]
case object None extends Option[Nothing]
trait Option[+A] {
/* returns None if None, or function applied to the some object */
def map[B](f: A => B): Option[B] = this match {
case None => None
case Some(a) => Some(f(a))
}
}
抛出的错误是:
$ scala
Welcome to Scala 2.12.0-20161021-070700-8684ae8 (OpenJDK 64-Bit Server VM, Java 1.8.0_112).
scala> :load tmp.scala
tmp.scala:17: error: pattern type is incompatible with expected type;
found : None.type
required: Option[A]
case None => None
^
tmp.scala:17: error: type mismatch;
found : None.type
required: Option[B]
case None => None
^
tmp.scala:18: error: constructor cannot be instantiated to expected type;
found : Some[A(in class Some)]
required: Option[A(in trait Option)]
case Some(a) => Some(f(a))
^
tmp.scala:18: error: type mismatch;
found : Some[B]
required: Option[B]
case Some(a) => Some(f(a))
^
我尝试了各种codefu,但无济于事,似乎由于过时的语法而无法正确检测子类?
使用粘贴内容的 :paste file.scala
,而不是解释每一行的 :load file.scala
。