Can I define companion classes / modules in the Scala interpreter?

It is often convenient to check the contents in the Scala interpreter. However, one problem I am facing is that I have to restructure the 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 REPL. As a result, I cannot be sure that my code will work when I get back to the "real source".

Is there a way to define companions in a REPL? Maybe something similar to

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

such that

 val v: A = "apple" 

will compile.

+4
source share
2 answers

It's close:

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

Or, if you put everything on one line:

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

... although in any case, you still have to import the implicit conversion to do the following work on your request:

 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 because every line that you enter in the REPL is enclosed in an object, and each subsequent line is nested in the previous one. This is done so that you can do the following things without getting override errors:

 val a = 5 val a = "five" 

(In fact, the second definition of a here is the shadow of the first.)

+10
source

In later versions, use may use the command: paste.

+2
source

All Articles