0

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

zjffdu
  • 25,496
  • 45
  • 109
  • 159

3 Answers3

1

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.

chengpohi
  • 14,064
  • 1
  • 24
  • 42
  • Thanks @chengpohi , Is there scala api that I can use ? I want to create some object at runtime and inject this object into my scala repl. – zjffdu Jul 20 '17 at 01:25
  • Hi @zjffdu, the above way create a init file, and when start **scala repl** it will automatically load the **init files** variables. if you want load this file in **repl runtime**, you can use `:load init.scala` after you start your repl. – chengpohi Jul 20 '17 at 01:39
  • If you don't want to create an intermediate file, you can do something like this too ` (echo 'val foo="bar"'; cat - ) | scala` – Dima Jul 20 '17 at 01:46
0

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}
Andrii Abramov
  • 10,019
  • 9
  • 74
  • 96
0

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

console / initialCommands := "import scala.util.*"
6infinity8
  • 298
  • 4
  • 10