I'm looking for a function in Scala that has similar functionality to getch. While using the console, I'd like to have my program display information based on what characters the user inputs (for example, if I was displaying a text, hitting n would show the next page, and p the previous). Right now I'm using readLine or readChar, but they require the user to hit Enter after each input, a bit annoying. Plus, in Eclipse plug-in's interpreter, the input character is shown, although I guess that might be unavoidable.
Asked
Active
Viewed 2,505 times
3 Answers
7
scala.Console.readChar
, aliased in in current incarnations of Scala as Predef.getChar
is the most direct way.
scala> readChar
res0: Char = !
UPDATE
This time without the pesky Enter
:
scala> Console.in.read.toChar
res0: Char = !

retronym
- 54,768
- 12
- 155
- 168
-
1I tried it also (scala 2.9.0.1 and java 1.6.0_24), but it requires me to press **Enter** – tenshi Aug 17 '11 at 21:26
-
I'll mark this as being the answer, since it's a Scala solution, although this is equivalent to Easy Angel's response. – Henry Henrinson Aug 17 '11 at 22:24
3
Use StdIn lib:
StdIn.readChar()

ebl
- 115
- 1
- 9
-
In sclala 2.11, this requires that one press Enter but it discards the Enter, which is handy. – F. P. Freely May 17 '17 at 18:01
-
This is nice, but if you just press enter, you get an exception: `Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0` – cstroe Dec 22 '22 at 18:45
2
You can try to use Java's Console that was added in 1.6. Here is REPL session:
scala> val r = System.console().reader()
r: java.io.Reader = java.io.Console$LineReader@1d97efc
scala> r.read.toChar
res8: Char = t
during repl session I pressed t key after executing second expression
reed
method does not require Enter and returns as soon as you press key.

tenshi
- 26,268
- 8
- 76
- 90
-
Ah, I should've imagined there was a Java solution to this. It worked, cheers. – Henry Henrinson Aug 17 '11 at 21:04