簡體   English   中英

在構造函數Scala上使用模式匹配進行類型不匹配

[英]Type mismatch using pattern matching on constructors scala

我正在嘗試在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)
             ^

提前致謝!

您將exists()放入SmartStream對象(即單例)中。 這意味着thisSmartStream.type類型,永遠不能是其他任何類型。

如果將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)
    }
  }
}

設計中可能還存在其他缺陷,但是至少可以進行編譯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM