3

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.

Henry Henrinson
  • 5,203
  • 7
  • 44
  • 76

3 Answers3

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
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