Learn through the super-clean Baeldung Pro experience:
>> Membership and Baeldung Pro.
No ads, dark-mode and 6 months free of IntelliJ Idea Ultimate to start with.
Last updated: March 18, 2024
In this tutorial, we’ll see how to read user input using Scala.
Reading the user input is straightforward as we just need to use the StdIn.readLine() method:
scala> val line = scala.io.StdIn.readLine()
$ some user input
val line: String = some user input
If we want to read more specific types, the StdIn class has many auxiliary methods for that such as readBoolean, readByte, readChar, readDouble, readInt, readFloat, and readLong:
scala> val i = scala.io.StdIn.readInt()
$ 42
val i: Int = 42
scala> val i = scala.io.StdIn.readInt()
$ abc
java.lang.NumberFormatException: For input string: "abc"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at scala.io.StdIn.readInt(StdIn.scala:122)
at scala.io.StdIn.readInt$(StdIn.scala:117)
at scala.io.StdIn$.readInt(StdIn.scala:241)
(...)
scala> val b = scala.io.StdIn.readBoolean()
True
val b: Boolean = true
scala> val b = scala.io.StdIn.readBoolean()
abc
val b: Boolean = false
We should notice that these methods rely on String conversions. As such, if the input is not parsable, an exception may be thrown as we saw with the integer parsing, or some implicit conversion can be done as we saw with the boolean example.
In this article, we saw how to read user input as any of the Scala basic types.