在构造函数Scala上使用模式匹配进行类型不匹配

时间:2019-04-27 01:31:34

标签: scala generics pattern-matching higher-kinded-types

我正在尝试在Scala(通用流)中定义一个HKT,我不确定为什么在尝试实现exist方法时会出现类型不匹配错误:

到目前为止,这是我的代码

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)
    }
  }
}

我得到的错误是:

    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)
             ^

谢谢!

1 个答案:

答案 0 :(得分:3)

您要将exists()放在SmartStream对象(即单例)中。这意味着this的类型为SmartStream.type,不能再为其他任何内容。

如果将exists()移至特征,并删除type参数,则事物将编译。

sealed trait SmartStream[+A] {
  def exists(p : A => Boolean) : Boolean = {
    this match {
      case Nil => false
      case Cons(h, t) => p(h()) || t().exists(p)
    }
  }
}

设计中可能还存在其他缺陷,但至少可以编译。

相关问题