How to inject custom object into scala repl when initializing scala repl

267 Views Asked by At

I'd like to custom the scala repl by injecting some custom value when starting scala repl. What kind of api that I can use for that ? Any difference between scala 2.10 and 2.11 ? Thanks

3

There are 3 best solutions below

0
On

If you are using sbt then there is a parameter that achieves that:

console / initialCommands := "import scala.util.*"
3
On

You can use scala -i or scala -I to load the init file:

scala -help
 -i <file>    preload <file> before starting the repl
 -I <file>    preload <file>, enforcing line-by-line interpretation
 ...

so you can create your custom file when start, like creating init.scala with:

val x = "Hello"
val y = "World"

and start scala -i init.scala

Welcome to Scala 2.12.2 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_71).
Type in expressions for evaluation. Or try :help.

scala> y
res0: String = Hello

scala> x
res1: String = World

and about the difference of scala 2.10 and scala 2.11, there should be no difference for this.

0
On

My solution was simply to define an alias in ~/.bashrc:

alias sc="scala -i ~/.scalarc"

I often use UUID objects from java.util package so it makes sense for me to predefine such import:

~/.scalarc:

import java.util.UUID
import scala.util.{Try, Success, Failure}
import scala.util.{Either, Left, Right}