Ranjit Jhala
Ranjit Jhala

Reputation: 1242

Code compiles with scalac but not in REPL

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
                  ^

Upvotes: 0

Views: 252

Answers (1)

dhg
dhg

Reputation: 52701

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

Upvotes: 2

Related Questions