Question

I have the following code:

abstract class AExp {
  def eval : Int = this match {
    case Num(n) => n
    case Add(e1, e2) => e1.eval + e2.eval
  }
}

case class Num(n : Int) extends AExp
case class Add(e1 : AExp, e2 : AExp) extends AExp

case class Prd(e1 : AExp, e2 : AExp) extends AExp {
  override def eval : Int = e1.eval * e2.eval
}

It works fine under Scala 2.8 here but does not work under 2.10 when I load it into the REPL. I get tons of errors:

scala> :l aexp.scala
Loading aexp.scala...
<console>:9: error: not found: value Num
           case Num(n) => n
                ^
<console>:9: error: not found: value n
           case Num(n) => n
                          ^
<console>:10: error: not found: value Add
           case Add(e1, e2) => e1.eval + e2.eval
                ^
<console>:10: error: not found: value e1
           case Add(e1, e2) => e1.eval + e2.eval
                               ^
<console>:7: error: not found: type AExp
       case class Num(n : Int) extends AExp
                                       ^
<console>:7: error: not found: type AExp
       case class Add(e1 : AExp, e2 : AExp) extends AExp
                                                    ^
<console>:7: error: not found: type AExp
       case class Add(e1 : AExp, e2 : AExp) extends AExp
                           ^
<console>:7: error: not found: type AExp
       case class Add(e1 : AExp, e2 : AExp) extends AExp
                                      ^
<console>:7: error: not found: type AExp
       case class Prd(e1 : AExp, e2 : AExp) extends AExp {
                                                    ^
<console>:7: error: not found: type AExp
       case class Prd(e1 : AExp, e2 : AExp) extends AExp {
                           ^
<console>:7: error: not found: type AExp
       case class Prd(e1 : AExp, e2 : AExp) extends AExp {
                                      ^

But the same code works fine in :paste mode under the 2.10 REPL. What is going on here? What does :load do and what does it not do?

Was it helpful?

Solution

As :help says,

:load
load and interpret a Scala file

it loads file and interprets it line-by-line, just like it would interpret individual lines that you feed to REPL, whereas :paste interpret whole chunk of code as an atomical unit.

The error, as you can predict is that repl sees

abstract class AExp {
  def eval : Int = this match {
    case Num(n) => n
    case Add(e1, e2) => e1.eval + e2.eval
  }
}

But know nothing about Num and Add types -- they aren't defined yet. The trick to make :load work the way you wanted to is to wrap all your code in some super object, e.g.:

object InterpretAsUnit {
  // all your code goes there
}

P.S. funny fact, is that scala -i <your path> nearly identical to scala and then :load <your path>

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top