Home »
Scala
REPL in Scala - Working with Scala Interpreter
By IncludeHelp Last updated : November 16, 2024
Scala REPL
REPL in Scala stands for Read-Evaluate-Print-Loop.
It is a command-line interpreter that is used to run Scala programming in your system on terminal or command prompt.
Working of REPL interpreter
As its name depicts its works on read-evaluate-print-repeat principle. This means REPL first reads the statement from the command line then evaluates it to find the result which will then be printed on the output screen. Then the process of read comes again and this cycle goes on until the given program ends. The interpreter can access the results from the previous compilation if the current line of code requires it.
Some Important Feature of REPL
- The IMain of REPL is bound to $intp.
- The last exception of REPL is bound to $lastException.
- You can use the tab for completion of code i.e. pressing the tab will return all available methods for that object.
- You can get the list of commands you can type REPL by :help command.
- The command used for loading a file to get input on REPL is :load.
- The command to enter power mode and import compiler components is :power.
- The :paste command is with a class or object to make it companion.
- To disable code wrapping or to define the code as a package, we can use the :paste -raw command.
- To inspect class artifacts, the :javap command is used.
- Use can even change the settings of the compiler in REPL using the :settings command.
Setting REPL
You can set up the runtime environment for Scala easily using the steps stated in this article.
After installing the environment starting the REPL is quite easy. You just need to type Scala as stated below in your command prompt.
> $scala
This will start the REPL interpreter and show some details about Scala install version on your system.
Welcome to Scala 2.13.0 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_131).
Type in expressions for evaluation. Or try :help.
After this prompt, there will be space for you to write your code line by line. You will see something like this:
scala> _
After this, you can write your code line by line and after every return (line end which is when you hit enter). The code in the line will be compiled. Let's see a program for some basic things in REPL.
scala> "Hello World!"
res0: Hello World!
scala> val val1 = 654, val2 = 45
val1 = 654
val2 = 45
scala> val1 * val2
res1: 29430
scala> val arr = Array(2, 1, 6, 3)
arr: Array[Int] = Array(2, 1, 6, 3)
That's all about working with REPL in Scala.
Is there any alternative to REPL?
Yes, there is an alternative to REPL in Scala. It is Ammonite project.