首页 > 解决方案 > 模式类型与教科书示例中的预期类型不兼容

问题描述

我正在阅读 Underscore 的 Essential Scala 教科书,当我尝试使用 :load 命令从命令行使用其中一个示例时,我得到了错误。[编辑] 我说的是命令行,我的意思是控制台。

我已经将代码本身放入一个文件中,然后尝试使用 :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

标签: scala

解决方案


在 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>

ctrl-D粘贴完所有行后,只需按下 PS 。


推荐阅读