Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/57.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
scala中的模式匹配问题:“;错误:无法将构造函数实例化为预期类型;_Scala_Pattern Matching - Fatal编程技术网

scala中的模式匹配问题:“;错误:无法将构造函数实例化为预期类型;

scala中的模式匹配问题:“;错误:无法将构造函数实例化为预期类型;,scala,pattern-matching,Scala,Pattern Matching,我试图在trait中定义toList方法,如下所示: sealed trait Stream[+A] { def toList: List[A] = this match { case Empty => List() case Cons(h, t) => h()::t().toList() } } case object Empty extends Stream[Nothing] case class Cons[+A](h: () => A,

我试图在trait中定义
toList
方法,如下所示:

sealed trait Stream[+A] {
  def toList: List[A] = this match {
      case Empty => List()
      case Cons(h, t) => h()::t().toList()
  }
}

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, tl: => Stream[A]): Stream[A] = {    
    lazy val head = hd  
    lazy val tail = tl
    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: _*))
}
我发现以下编译错误:

stream.scala:16: error: pattern type is incompatible with expected type;
 found   : Empty.type
 required: Stream[A]
      case Empty => List()
               ^
stream.scala:17: error: constructor cannot be instantiated to expected type;
 found   : Cons[A(in class Cons)]
 required: Stream[A(in trait Stream)]
      case Cons(h, t) => h()::t().toList()
               ^

有人能提供建议吗?

您看到的错误来自REPL。REPL中的每个完整语句都打包在一个对象中,以便它可以生成和报告中间值:
res0
res1
,等等

当您
:加载
文件时,就好像您单独键入了每一行一样,但是如果您复制/粘贴,
:pa
,代码将进入REPL,它将工作(在您解决
()
问题之后)


另一个选项是将所有代码包装到外部
对象中。然后,当您
:加载
文件时,它将作为一个单元而不是作为单独的对象和类进行编译。

供您参考,我从scala REPL加载源文件,如下所示:
scala>:load stream.scala
()
之后。toList
不属于此处,但在其他地方,看起来还好吧?至少,它的编译版本是2.12.5-2.12.7。非常感谢您的回复!