[英]Type mismatch using pattern matching on constructors scala
I'm trying to define a HKT in Scala (a generic stream) and I'm not sure why I'm getting a type mismatch error while trying to implement the exists method: 我正在尝试在Scala(通用流)中定义HKT,但不确定在尝试实现exist方法时为什么会出现类型不匹配错误:
Here's my code so far 到目前为止,这是我的代码
sealed trait SmartStream[+A]
case object Nil extends SmartStream[Nothing]
case class Cons[+A](h : () => A, t : () => SmartStream[A]) extends SmartStream[A]
object SmartStream {
def nil[A] : SmartStream[A] = Nil
def cons[A](h : => A, t : => SmartStream[A]) : SmartStream[A] = {
lazy val g = h
lazy val u = t
Cons(() => g, () => u)
}
def apply[A](as: A*) : SmartStream[A] = {
if (as.isEmpty) nil
else cons( as.head, apply(as.tail: _*))
}
def exists[A](p : A => Boolean) : Boolean = {
this match {
case Nil => false
case Cons(h, t) => p(h()) || t().exists(p)
}
}
}
The error I'm getting is: 我得到的错误是:
ScalaFiddle.scala:21: error: pattern type is incompatible with expected type;
found : ScalaFiddle.this.Nil.type
required: ScalaFiddle.this.SmartStream.type
case Nil => false
^
ScalaFiddle.scala:22: error: constructor cannot be instantiated to expected type;
found : ScalaFiddle.this.Cons[A]
required: ScalaFiddle.this.SmartStream.type
case Cons(h, t) => p(h()) || t().exists(p)
^
Thanks in advance! 提前致谢!
You're putting exists()
in the SmartStream
object (ie singleton). 您将exists()
放入SmartStream
对象(即单例)中。 That means this
is type SmartStream.type
and can never be anything else. 这意味着this
是SmartStream.type
类型,永远不能是其他任何类型。
If you move exists()
to the trait, and remove the type parameter, things will compile. 如果将exists()
移至特征,并删除类型参数,则事物将编译。
sealed trait SmartStream[+A] {
def exists(p : A => Boolean) : Boolean = {
this match {
case Nil => false
case Cons(h, t) => p(h()) || t().exists(p)
}
}
}
There may be other deficiencies in the design, but at least this compiles. 设计中可能还存在其他缺陷,但是至少可以进行编译。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.