必须指定参数类型

时间:2017-05-12 08:20:01

标签: scala

我有一个Stream特征,它包含以下方法:

sealed trait Stream[+A] {

  def takeWhile2(f: A => Boolean): Stream[A] =
    this.foldRight(Stream.empty[A])((x, y) => {
      if (f(x)) Stream.cons(x, y) else Stream.empty
    })

  @annotation.tailrec
  final def exists(p: A => Boolean): Boolean = this match {
    case Cons(h, t) => p(h()) || t().exists(p)
    case _ => false
  }
}

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, t1: => Stream[A]): Stream[A] = {
    lazy val head = hd
    lazy val tail = t1

    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: _*))

}

查看takeWhile2正文,它会调用foldRight函数。

当我通过Stream.empty而不是Stream.empty[A]时,我会遇到编译错误,为什么?

1 个答案:

答案 0 :(得分:0)

那是因为当(x,y)为真时,您已将Stream.empty[A]投放为f(x),但当f(x)为假时,它将返回Stream.empty[Nothing],即如果您没有指定使用dataType默认值Nothing。因此Stream[A](预期的返回类型)与Stream[Nothing]

的返回值不匹配