
- Scala - Home
- Scala - Overview
- Scala - Features
- Scala - Environment Setup
- Scala - Build Tool (SBT)
- Scala - REPL
- Scala - Dot & Dotty
- Scala - Basic Syntax
- Scala - Hello World Program
- Scala - Identifiers
- Scala - Keywords
- Scala - Comments
- Scala - Code Blocks
- Scala - Semicolon
- Scala - Constructs
- Scala - Expressions
- Scala - Input and Output
- Scala - Optional Braces
- Scala - Underscore (_)
- Data Types and Variables
- Scala - Data Types
- Scala - Type Bounds
- Scala - Context Bound
- Scala - Variances
- Scala - Type Hierarchy
- Scala - Variables
- Scala - Variable Scopes
- Scala - Literals
- Scala - Numeric Types
- Scala - Boolean Types
- Scala - Char Type
- Scala - Unit Types
- Scala - Strings
- Scala - Arrays
- Scala - Null Type
- Scala - Nothing
- Scala - Any Type
- Scala - AnyRef Type
- Scala - Unified Types
- Scala - Dates and Times
- Scala - Ranges
- Scala - Multidimensional Arrays
- Scala - WrappedArray
- Scala - StringBuilder
- Scala - String Interpolation
- Scala - StringContext
- Scala - Type Casting
- Scala var vs val
- Scala Operators
- Scala - Operators
- Scala - Rules for Operators
- Scala - Arithmetic Operators
- Scala - Relational Operators
- Scala - Logical Operators
- Scala - Bitwise Operators
- Scala - Assignment Operators
- Scala - Operators Precedence
- Scala - Symbolic Operators
- Scala - Range Operator
- Scala - String Concatenation Operator
- Scala Conditional Statements
- Scala - IF ELSE
- Scala - IF-ELSE-IF-ELSE Statement
- Scala - Nested IF-ELSE Statement
- Scala Loop Statements
- Scala - Loop Statements
- Scala - while Loop
- Scala - do-while Loop
- Scala - Nested Loops
- Scala - for Loop
- Scala - break Statement
- Scala - yield Keyword
- Scala Classes & Objects
- Scala - Classes & Objects
- Scala - Constructors
- Scala - Auxiliary Constructor
- Scala - Primary Constructor
- Scala - This Keyword
- Scala - Nested Classes
- Scala - Getters and Setters
- Scala - Object Private Fields
- Scala - Singleton Object
- Scala - Companion Objects
- Scala - Creating Executable Programs
- Scala - Stateful Object
- Scala - Enumerations
- Scala - Polymorphism
- Scala - Access Modifiers
- Scala - Apply Method
- Scala - Update Methods
- Scala - UnapplySeq Method
- Scala - Inheritance
- Scala - Extending a Class
- Scala - Method Overloading
- Scala - Method Overriding
- Scala - Generic Classes
- Scala - Generic Functions
- Scala - Superclass Construction
- Scala Methods & Functions
- Scala - Functions
- Scala - Main Methods
- Scala - Functions Call-by-Name
- Scala - Functions with Named Arguments
- Scala - Function with Variable Arguments
- Scala - Recursion Functions
- Scala - Default Parameter Values
- Scala - Functions without Parameters
- Scala - Implicit Parameters
- Scala - Higher-Order Functions
- Scala - Nested Functions
- Scala - Extension Methods
- Scala - Anonymous Functions
- Partially Applied Functions
- Scala - Lazy Val
- Scala - Pure Function
- Scala - Currying Functions
- Scala - Control Abstractions
- Scala - Corecursion
- Scala - Unfold
- Scala - Tail Recursion
- Scala - Infinite Sequences
- Scala - Dynamic Invocation
- Scala - Lambda Expressions
- Scala Collections
- Scala - Collections
- Mutable and Immutable Collections
- Scala - Lists
- Scala - Sets
- Scala - Maps
- Scala - TreeMap
- Scala - SortedMap
- Scala - Tuples
- Scala - Iterators
- Scala - Options
- Scala - Infinite Streams
- Scala - Parallel Collections
- Scala - Algebraic Data Types
- Scala Pattern Matching
- Scala - Pattern Matching
- Scala - Type Patterns
- Scala - Exception Handling
- Scala - Extractors
- Scala - Regular Expressions
- Scala Files I/O
- Scala - Files I/O
- Scala Advanced Concepts
- Scala - Closures
- Scala - Futures
- Scala - Promises
- Scala - Traits
- Scala - Trait Mixins
- Scala - Layered Traits
- Scala - Trait Linearization
- Scala - Sealed Traits
- Scala - Transparent Traits
- Scala - Literal Type Arithmetic
- Scala - Inline keyword
- Scala - Def, Var & Val
- Scala - Dropped Features
- Scala - BDD Testing
Scala - Input and Output
You can take input from the user and can also display it as output in Scala. This is useful when you work with loops, conditional statements and other Scala constructs. Here, we have discussed command-line input and output with Scala.
Writing Output
You can display output in various ways, you can output to standard out (STDOUT).
Print with newline
You can use `println` command to print statements and with newline.
println("This is statement and there will be a newline after it")
For example,
object PrintExample { def main(args: Array[String]) { println("This is a statement, and there will be a newline after it") println("You can print multiple lines with different statements.") } }
Print without newline
You can use `print` command to print statements and without newline.
print("This is statement but there will not be any newline after it, till you do")
For example,
object PrintExample { def main(args: Array[String]) { print("This is a statement, but there will not be any newline after it,") print("till you do.") } }
Print to standard error (STDERR)
System.err.printlin("This error has occurred")
For example,
object ErrorExample { def main(args: Array[String]) { System.err.println("This error has occurred") System.err.println("Another error message.") } }
In these examples, first two use `println` and `print` function on standard output (STDOUT) and last one `System.err.println` function on standard error (STDERR). Note that when we use commands like, println, String, Int, Float etc, you need not to import them explicitly.
Reading Input
You can read input from the console and from other sources using various methods and libraries.
Reading from the Console
You can use `scala.io.StdIn` for console input. You can read a line of text from the console.
val input = scala.io.StdIn.readLine("Enter something: ") println(s"You entered: $input")
The command `readLine` is the easiest way which belongs in `scala.io.package`. So you need to import it before use. Like,
import scala.io.StdIn.readLine
Then you use it, for example,
import scala.io.StdIn.readLine object TemperatureConversion extends App { print("Enter temperature in Celsius: ") val celsius = readLine().toDouble val fahrenheit = (celsius * 9/5) + 32 println(s"$celsiusC is equal to $fahrenheitF") }
Then you can compile it using `scalac`,
$ scalac TemperatureConversion.scala
Then execute it
$ scala TemperatureConversion
You will need to provide required input here.
You can also use `scala.io.StdIn.readInt()` and `scala.io.StdIn.readDouble()` etc to read specific data types input from the console.
Reading from Files
You can use `scala.io.Source` for file input.
import scala.io.Source val source = Source.fromFile("input.txt") val lines = source.getLines() for (line <- lines) { println(line) } source.close()
Reading from other Sources
You can also use `scala.io.StdIn.readLine()` and `scala.io.StdIn.readChar()` to read input from standard input. These are some methods to read input input in Scala.
These are standard way to read integer values in Scala:
Method | Description |
---|---|
readBoolean() | Reads a Boolean value from an entire line from stdin. |
readByte() | Reads a Byte value from an entire line from stdin. |
readChar() | Reads a Char value from an entire line from stdin. |
readDouble() | Reads a Double value from an entire line from stdin. |
readFloat() | Reads a Float value from an entire line from stdin. |
readInt() | Reads an Int value from an entire line from stdin. |
readLine(text: String, args: Any*) | Prints formatted text to stdout and reads a full line from stdin. |
readLine() | Reads a full line from stdin. |
readLong() | Reads a Long value from an entire line from stdin. |
readShort() | Reads a Short value from an entire line from stdin. |
readf(format: String) | Reads in structured input from stdin as specified by the format specifier. |
readf1(format: String) | Reads in structured input from stdin as specified by the format specifier, returning only the first value extracted, according to the format specification. |
readf2(format: String) | Reads in structured input from stdin as specified by the format specifier, returning only the first two values extracted, according to the format specification. |
readf3(format: String) | Reads in structured input from stdin as specified by the format specifier, returning only the first three values extracted, according to the format specification. |
Note
You can take user String input in Scala using `readLine()` and `Scanner` class.
For example, using `readLine()`
import scala.io.StdIn._ object ReadLineExample { def main(args: Array[String]): Unit = { println("Enter your favorite color: ") val color = readLine() println("Your favorite color is: " + color) } }
Using `Scanner`
import java.util.Scanner object ScannerExample { def main(args: Array[String]): Unit = { val scanner = new Scanner(System.in) println("Enter your favorite food: ") val food = scanner.nextLine() println("Your favorite food is: " + food) } }
If you want to read many inputs from the same line, then you need to use `Scanner` object for it.
import java.util.Scanner