Scala子类模式匹配

Scala子类模式匹配

本文介绍了Scala子类模式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从Scala函数式编程一书中运行代码,这本书似乎适用于较旧版本的scala(从)。 tmp.scala:

 密封特质选项[+ A] 
案例类某些[+ A](get:A )扩展选项[A]
案例对象无扩展选项[无]

特征选项[+ A] {
/ *返回无如果无或函数应用于某些对象* /
def map [B](f:A => B):选项[B] =此匹配{
case None =>无
案例Some(a)=>一些(f(a))
}
}

是:

  $ scala 
欢迎来到Scala 2.12.0-20161021-070700-8684ae8(OpenJDK 64位服务器VM,Java 1.8.0_112)。
scala> :load tmp.scala

tmp.scala:17:error:模式类型与预期类型不兼容;
找到:None.type
required:Option [A]
case None =>无
^
tmp.scala:17:错误:类型不匹配;
找到:None.type
required:Option [B]
case None =>无
^
tmp.scala:18:错误:构造函数无法实例化为预期类型;
found:Some [A(in class Some)]
required:Option [A(in trait Option)]
case Some(a)=>一些(f(a))
^
tmp.scala:18:错误:类型不匹配;
找到:有些[B]
需要:选项[B]
案例某些(a)=>一些(f(a))
^

我尝试了各种各样的codefu,但无济于事,它似乎没有正确地检测子类由于过时的语法? 使用:paste file.scala ,它粘贴内容,而不是:load file.scala ,它解释每一行。


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?

解决方案

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

这篇关于Scala子类模式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 11:38