Scala 错误 "pattern type is incompatible with expected type"

标签 scala

我正在研究“Scala 中的函数式编程”一书。第 5.2 章从以下代码开始:

sealed trait Stream[+A]
case object Empty extends Stream[Nothing]
case class Cons[+A](h: () => A, t: () => Stream[A]) extends Stream[A]

object Stream {
  def cons[A](hd: => A, tl: => Stream[A]): Stream[A] = {
    lazy val head = hd
    lazy val tail = tl
    Cons(() => head, () => tail)
  }

  def empty[A]: Stream[A] = Empty

  def apply[A](as: A*): Stream[A] =
    if (as.isEmpty) empty else cons(as.head, apply(as.tail: _*))

}

然后给出以下定义:
  def headOption: Option[A] = this match {
      case Empty => None
      case Cons(h, t) => Some(h())
    }

我认为它应该是伴随对象的一部分。为了不立即出现编译错误,我添加了“headOption[A]”。但是,当我将结果包含到“对象流”中时,我收到错误“模式类型与预期类型不兼容;发现:需要 myPackage.Empty.type:myPackage.Stream.type”并带有下划线“Empty”。

我在这里有点失落。我究竟做错了什么?

最佳答案

它应该是 trait Stream[+A] 的一部分.

这里this指的是Stream (特征流不是伴随对象)。 Stream可以 Empty或者它可以是 Cons .所以模式匹配 this说得通。
headOption如果可用,给出流的第一个元素。

    case object Empty extends Stream[Nothing]

    case class Cons[+A](h: () => A, t: () => Stream[A]) extends Stream[A]

    sealed trait Stream[+A] {
      def headOption: Option[A] = this match {
        case Empty => None
        case Cons(h, t) => Some(h())
      }
    }



    object Stream {

      def cons[A](hd: => A, tl: => Stream[A]): Stream[A] = {
        lazy val head = hd
        lazy val tail = tl
        Cons(() => head, () => tail)
      }

      def empty[A]: Stream[A] = Empty

      def apply[A](as: A*): Stream[A] =
        if (as.isEmpty) empty else cons(as.head, apply(as.tail: _*))


    }

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

case object Empty extends Stream[Nothing]

case class Cons[+A](h: () => A, t: () => Stream[A]) extends Stream[A]

sealed trait Stream[+A] {

  def headOption: Option[A] = this match {
    case Empty => None
    case Cons(h, t) => Some(h())
  }

}

object Stream {

  def cons[A](hd: => A, tl: => Stream[A]): Stream[A] = {
    lazy val head = hd
    lazy val tail = tl
    Cons(() => head, () => tail)
  }

  def empty[A]: Stream[A] = Empty

  def apply[A](as: A*): Stream[A] =
    if (as.isEmpty) empty else cons(as.head, apply(as.tail: _*))

}

// Exiting paste mode, now interpreting.

defined object Empty
defined class Cons
defined trait Stream
defined object Stream

scala> Stream.cons(1, Empty).headOption
res0: Option[Int] = Some(1)

关于Scala 错误 "pattern type is incompatible with expected type",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40092788/

相关文章:

scala - 在 Scala 中调用反射案例类构造函数

scala - 为什么此Scala代码报告编译错误:递归值x需要类型

postgresql - Slick 2.0 通用 CRUD 操作

scala - Spark Streaming 中的批处理大小

java - 将 Scala 项目包含在 Java Maven 依赖项中

scala - 使用鹅毛笔时为 `exception during macro expansion: [error] scala.reflect.macros.TypecheckException`

scala - 为什么scalaz-stream中有两种网络io的实现?

scala - Spark joinWithCassandraTable() 映射多个分区键错误

scala - 我如何关闭 Finagle Thrift 客户端?

scala - 如何将每种类型的列分成两组?