Code compiles with scalac but not in REPL

白昼怎懂夜的黑 提交于 2019-12-13 04:45:40

问题


I have some code, say in Foo.scala that compiles readily with scalac, but I get a blizzard of errors when I boot up the REPL and say :load Foo.scala. I imagine this is standard and documented but can't seem to find any relevant information about it.

The file looks like this:

abstract class BST[A](implicit cmp: A => Ordered[A]) {
  def fold[B](f: (B, A) => B, acc: B): B = {
    this match {
      case Leaf()        => acc
    }                 
  } 
} 

case class Leaf[A]()(implicit cmp: A => Ordered[A]) extends BST[A]

And I get errors like so:

scala> :load BST3.scala
Loading BST3.scala...
<console>:10: error: constructor cannot be instantiated to expected type;
 found   : Leaf[A(in class Leaf)]
 required: BST[A(in class BST)]
             case Leaf()        => acc
                  ^

回答1:


It looks like :load tries to interpret the file block-by-block. Since your blocks are mutually-dependent, this is a problem.

Try using "paste mode" to paste multiple blocks into the REPL for Scala to compile together:

scala> :paste

// Entering paste mode (ctrl-D to finish)

abstract class BST[A](implicit cmp: A => Ordered[A]) {
  def fold[B](f: (B, A) => B, acc: B): B = {
    this match {
      case Leaf()        => acc
    }                 
  } 
} 

case class Leaf[A]()(implicit cmp: A => Ordered[A]) extends BST[A]

// Exiting paste mode, now interpreting.

defined class BST
defined class Leaf


来源:https://stackoverflow.com/questions/10343516/code-compiles-with-scalac-but-not-in-repl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!