Scala subclass pattern match

怎甘沉沦 提交于 2019-12-08 13:40:58

问题


I'm trying to run code from the book "Functional Programming in Scala" which seems to be made for an older version of scala (download from 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))
    }
}

The errors this throws are:

$ 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))
                                 ^

I tried all sorts of codefu on this, but to no avail, it seems like it's not detecting the subclasses properly due to outdated syntax?


回答1:


Use :paste file.scala, which pastes the content, instead of :load file.scala, which interprets each line.



来源:https://stackoverflow.com/questions/40900391/scala-subclass-pattern-match

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!