Read a String from Console Input in Scala
In a Scala console application, you can read text entered through standard input by using scala.io.StdIn.readLine(). The method waits for the user to enter a line and press Enter, then returns that line as a String.
This tutorial explains how to read a string from the Scala console, display an input prompt, use an imported readLine method, handle blank input, and safely process input when the end of the stream is reached.
Scala StdIn.readLine() Syntax
To read one complete line from standard input, call scala.io.StdIn.readLine().
val input: String = scala.io.StdIn.readLine()
You can also pass a prompt string to readLine. The prompt is displayed before Scala waits for the user’s input.
val input: String = scala.io.StdIn.readLine("Prompt: ")
The returned value does not include the newline produced when the user presses Enter. Under normal interactive use, the value contains the characters typed before that newline.
Scala Example to Read a String from Console
In this example, we shall read a string from console and print it to the console.
example.scala
object ReadInputExample {
def main(args: Array[String]) {
val name = scala.io.StdIn.readLine("Enter your name: ")
println("Hello "+name)
}
}
Output
Enter your name: Arjun
Hello Arjun
The text Enter your name: is the prompt. When the user enters Arjun and presses Enter, readLine stores Arjun in the variable name. The next statement joins that value with Hello and prints the result.
Importing StdIn.readLine in Scala
If a program reads several values, importing scala.io.StdIn.readLine can make repeated calls shorter.
import scala.io.StdIn.readLine
object ReadCityExample {
def main(args: Array[String]): Unit = {
val city = readLine("Enter your city: ")
println(s"You entered: $city")
}
}
Enter your city: Hyderabad
You entered: Hyderabad
The import does not change how input is read. It only allows the method to be called as readLine(...) instead of scala.io.StdIn.readLine(...).
Reading Multiple Strings from Scala Console Input
Call readLine once for each separate line of input. The following program asks for a first name and a last name.
import scala.io.StdIn.readLine
object ReadFullNameExample {
def main(args: Array[String]): Unit = {
val firstName = readLine("Enter your first name: ")
val lastName = readLine("Enter your last name: ")
println(s"Full name: $firstName $lastName")
}
}
Enter your first name: Arjun
Enter your last name: Kumar
Full name: Arjun Kumar
Each invocation waits for a new line. Spaces entered within a line are retained, so readLine can also read a full name or sentence in a single call.
Removing Extra Spaces from Scala String Input
User input can contain spaces before or after the meaningful text. Call trim when those surrounding spaces should be removed.
import scala.io.StdIn.readLine
object TrimInputExample {
def main(args: Array[String]): Unit = {
val username = readLine("Enter a username: ").trim
println(s"Username: '$username'")
}
}
The trim method removes leading and trailing whitespace. It does not remove spaces located between words.
Checking for Empty Scala Console Input
If the user presses Enter without typing any visible characters, readLine normally returns an empty string. After trimming the value, use isEmpty or nonEmpty to validate it.
import scala.io.StdIn.readLine
object ValidateNameExample {
def main(args: Array[String]): Unit = {
val name = readLine("Enter your name: ").trim
if (name.nonEmpty) {
println(s"Hello $name")
} else {
println("No name was entered.")
}
}
}
Checking the input before using it avoids producing output such as a greeting with no name.
Reading Console Input Until a Valid String Is Entered
A while loop can repeatedly request input until the user provides a non-empty string.
import scala.io.StdIn.readLine
object RequiredInputExample {
def main(args: Array[String]): Unit = {
var name = ""
while (name.isEmpty) {
name = readLine("Enter your name: ").trim
if (name.isEmpty) {
println("Name cannot be empty.")
}
}
println(s"Hello $name")
}
}
Enter your name:
Name cannot be empty.
Enter your name: Meera
Hello Meera
Handling End-of-Input with Scala StdIn.readLine
When standard input reaches end-of-file before another line is available, readLine can return null. This can occur when input is redirected from a file or when an end-of-input signal is sent in a terminal.
A null-safe program can wrap the result in Option before calling string methods such as trim.
import scala.io.StdIn.readLine
object SafeInputExample {
def main(args: Array[String]): Unit = {
val input = Option(readLine("Enter a value: "))
input match {
case Some(value) => println(s"You entered: ${value.trim}")
case None => println("No input was available.")
}
}
}
This distinction matters because an empty string means that a line was read but contained no text, whereas null indicates that no further line was available.
Reading a String with Console.readLine in Scala
Scala also exposes Console.readLine. For straightforward terminal input, scala.io.StdIn.readLine is generally clearer because it explicitly identifies standard input.
val message = Console.readLine("Enter a message: ")
println(message)
Whichever form is used, keep the choice consistent within the program so that the source of console input is easy to recognize.
Running a Scala Console Input Program
When using a local Scala installation, compile the source file and run the generated object from a terminal. For a file named ReadInputExample.scala, the commands are:
scalac ReadInputExample.scala
scala ReadInputExample
The program then pauses at readLine until input is supplied. Some online Scala compilers do not provide interactive standard input, so console-reading examples may need an input panel or a local terminal to run correctly.
Common Scala readLine Input Mistakes
- Calling string methods on end-of-input: Check for
null, or wrap the result withOption, when input may come from a redirected stream. - Assuming blank input is valid: Use
trimandnonEmptywhen the application requires visible text. - Expecting readLine to parse numbers: The method returns a string. Numeric text must be converted separately and validated.
- Using multiple readLine calls for one sentence: One call already reads the complete line, including spaces between words.
- Testing in a non-interactive environment: Confirm that the compiler or execution environment supports standard input.
Scala Console String Input FAQs
Which Scala method reads a string from standard input?
Use scala.io.StdIn.readLine(). It reads one complete line from standard input and returns it as a string.
How do I display a prompt before reading Scala console input?
Pass the prompt to the method, as in readLine("Enter your name: "). Scala displays the prompt before waiting for input.
Does Scala readLine include the Enter key or newline?
No. The returned string contains the text entered before the line-ending character, not the newline itself.
What does Scala readLine return for blank input?
If the user presses Enter without typing text, it normally returns an empty string. This is different from null, which can indicate end-of-input.
Can Scala readLine read a sentence containing spaces?
Yes. It reads the entire line, so spaces between words are retained until the user presses Enter.
Scala Console Input Editorial QA Checklist
- Confirm that every string-input example uses
scala.io.StdIn.readLine, an explicit import, or another clearly identified console API. - Check that prompts include suitable spacing or punctuation before the user’s typed value.
- Verify that output blocks match the exact prompts and string interpolation used in their examples.
- Distinguish empty input from end-of-file instead of treating both as the same value.
- Ensure that examples calling
trimaccount for the possibility ofnullwhen input can be redirected.
Summary of Reading Strings from Scala Console Input
Use scala.io.StdIn.readLine() to read a complete line of console input as a string. A prompt can be passed directly to the method, repeated calls can collect multiple lines, and methods such as trim, isEmpty, and nonEmpty can validate the result. When standard input may reach end-of-file, handle the possible null value before processing the string.
TutorialKart.com