scala错误"模式类型与预期类型不兼容"

时间:2016-10-17 17:58:37

标签: 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]"。但是当我将结果包含在"对象流"我收到错误"模式类型与预期类型不兼容; found:myPackage.Empty.type required:myPackage.Stream.type"与"空"下划线。

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

1 个答案:

答案 0 :(得分:2)

它应该是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)