This post will discuss how to read multiline data from the console in Kotlin.

1. Using Scanner

We can use two scanners, where the first scanner fetches each line with the Scanner.nextLine() function, and the second scanner scan through it using Scanner.next().

Download Code

 
The above solution can be optimized to only use a single scanner. The idea is to read tokens from each line using the split() function from the String class.

Download Code

 
Here’s equivalent code using only Scanner.next():

Download Code

2. Using BufferedReader

Another option to read multiline input from the console in Kotlin is using the BufferedReader class, which is synchronized. The following example demonstrates this by reading each line with the readLine() function and then using the split() function to split it into the individual tokens (using whitespace as a separator).

Download Code

 
To close all resources properly, consider using the use block:

Download Code

That’s all about reading multiline data from the console in Kotlin.