Несоответствие типов при использовании сопоставления с образцом на конструкторах scala - PullRequest
0 голосов
/ 27 апреля 2019

Я пытаюсь определить HKT в Scala (общий поток), и я не уверен, почему я получаю ошибку несоответствия типов при попытке реализовать метод существующие:

Вот мой кодпока

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 Ответ

3 голосов
/ 27 апреля 2019

Вы помещаете exists() в объект SmartStream (т.е. синглтон).Это означает, что this имеет тип SmartStream.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)
    }
  }
}

Возможны другие недостатки в дизайне, но по крайней мере это компилируется.

...