Authors Top

We’re starting a new Scala area. If you have a few years of experience in the Scala ecosystem, and you’re interested in sharing that experience with the community, have a look at our Contribution Guidelines.

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()
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.

3. Conclusion

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

Authors Bottom

We’re starting a new Scala area. If you have a few years of experience in the Scala ecosystem, and you’re interested in sharing that experience with the community, have a look at our Contribution Guidelines.

Comments are closed on this article!