模式类型与教科书示例中的预期类型不兼容

时间:2019-05-03 14:21:15

标签: scala

我正在研究Underscore的Essential Scala教科书,当我尝试使用:load命令在命令行中使用示例之一时,出现错误。 [edit]我说过命令行,我指的是控制台。

我已经将代码本身放入了文件中,然后尝试通过:load命令使用它。

sealed trait IntList {
  def product: Int =
    this match {
      case End => 1
      case Pair(hd, tl) => hd * tl.product
    }
}
case object End extends IntList
final case class Pair(head: Int, tail: IntList) extends IntList

我希望代码可以编译并可以使用,但是我得到以下消息:

 error: pattern type is incompatible with expected type;
 found   : End.type
 required: IntList
      case End => 1

error: constructor cannot be instantiated to expected type;
 found   : Pair
 required: IntList
      case Pair(hd, tl) => hd * tl.product

1 个答案:

答案 0 :(得分:0)

在Scala REPL中使用:paste命令:

scala> :paste
// Entering paste mode (ctrl-D to finish)

sealed trait IntList {
  def product: Int =
    this match {
      case End => 1
      case Pair(hd, tl) => hd * tl.product
    }
}
case object End extends IntList
final case class Pair(head: Int, tail: IntList) extends IntList

// Exiting paste mode, now interpreting.

defined trait IntList
defined object End
defined class Pair

scala>

P.S。完成所有行的粘贴后,只需按ctrl-D

相关问题