1. Overview

In this tutorial, we’ll see how to read user input using Scala.

2. Getting User Input

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()
val b: Boolean = true

scala> val b = scala.io.StdIn.readBoolean()
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.

3. Conclusion

In this article, we saw how to read user input as any of the Scala basic types.

Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.