Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to echo user input in Scala REPL?

I'm teaching an introductory programming class, using Scala. We are starting with the REPL. The REPL has a bug in that, when the student enters a readLine command, their input is not echoed. Is there some workaround that I can suggest or provide?

I don't have this trouble when using Eclipse, but it will be some weeks before I introduce Eclipse to my students.

like image 404
David Matuszek Avatar asked Aug 31 '13 18:08

David Matuszek


People also ask

How to take input from user in scala?

println ( "Hello" ) // Console is imported by default, so it's not really needed, just use println println ( "World" ) // readLine lets you prompt the user and read their input as a String val name = readLine ( "What's your name? " ) // readInt lets you read an Int, but you have to prompt the user manually print ( "How ...

What is a REPL Scala?

The Scala REPL (“Read-Evaluate-Print-Loop”) is a command-line interpreter that you use as a “playground” area to test your Scala code. To start a REPL session, just type scala at your operating system command line, and you'll see this: $ scala Welcome to Scala 2.13.0 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_131).


1 Answers

You can use power mode to get access to the REPL's reader; it will give you a fully working readLine:

scala> :power
** Power User mode enabled - BEEP WHIR GYVE **
** :phase has been set to 'typer'.          **
** scala.tools.nsc._ has been imported      **
** global._, definitions._ also imported    **
** Try  :help, :vals, power.<tab>           **

scala> repl.in.readLine("enter something: ")
enter something: hello world
res0: String = hello world

scala>

Edit: as @som-snytt pointed out, in 2.11 you can use reader instead of repl.in in the above code, which is both shorter and easier to remember.

like image 73
gourlaysama Avatar answered Nov 12 '22 06:11

gourlaysama