Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to define companion classes/modules in the Scala interpreter?

Tags:

scala

It's often convenient to test things out in the Scala interpreter. However, one issue I run into is that I have to restructure code that uses implicit conversions because defining an object with the same name as an existing class does not make it a companion module in the REPL. As a result, I can't be confident my code will still work when I translate back to "real source".

Is there a way to define companions in the REPL? Maybe something along the lines of

bigblock {
   class A

   object A {
      implicit def strToA(s: String): A = // ... 
   }
}

such that

val v: A = "apple"

will compile.

like image 654
Aaron Novstrup Avatar asked Dec 12 '22 20:12

Aaron Novstrup


2 Answers

That's close:

object ABlock {
   class A

   object A {
      implicit def strToA(s: String): A = // ... 
   }
}
import ABlock._

Or, the following, if you put everything on one line:

class A; object A { implicit def strToA(s: String): A = // ... } }

...though either way you'll still need to import the implicit conversion to make the following work as you requested:

import ABlock.A.strToA  // for the form with the enclosing object
import A.strToA         // for the one-line form without an enclosing object
val v: A = "apple"

The reason you need to do this is that every line you enter at the REPL is enclosed in an object and each subsequent one is nested within the immediately preceding one. This is done so you can do things like the following without getting redefinition errors:

val a = 5
val a = "five"

(Effectively, the second definition of a here shadows the first.)

like image 67
Randall Schulz Avatar answered Mar 08 '23 23:03

Randall Schulz


With more recent versions use can use the :paste command.

like image 25
srparish Avatar answered Mar 08 '23 22:03

srparish