【问题标题】:Pattern type is incompatible with expected type in textbook example模式类型与教科书示例中的预期类型不兼容
【发布时间】:2019-05-10 22:02:10
【问题描述】:

我正在阅读 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 项目中并运行 sbt comile 对我有用。你用的是什么版本的scala? :load 命令是什么?
  • 嗨 - 我刚刚编辑了这个问题,我意识到我使用了错误的术语,我说的是命令行,但我的意思是控制台。我在 scala 控制台中,并使用 ':load filename' 命令,这给出了我提到的错误。目前我只知道如何使用 Scala 控制台。
  • Scala 版本 2.12.7
  • 由于代码在常规 sbt 项目中编译但在控制台中不起作用,我建议您远离控制台。如果这是不可能的尝试在控制台中输入代码而不是加载文件并检查行为是否仍然相同
  • @OgladrKjarr 使用 :paste file 而不是 :load file stackoverflow.com/questions/7383436/…

标签: scala


【解决方案1】:

在 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

【讨论】:

    猜你喜欢
    • 2018-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多