Part 02 / Topic 7 of 8
Reading from standard input: readln()
readln() reads one line typed at the terminal and hands it back as a plain, non-null String —
the function to reach for whenever a Kotlin program needs to ask the person running it for something.
fun main() {
println("Enter the subtotal in rupees:")
val subtotalLine = readln() // readln() reads one line and returns a plain String, never null
val subtotal = subtotalLine.trim().toDouble()
println("Enter the number of diners:")
val dinersLine = readln()
val diners = dinersLine.trim().toInt()
val perHead = subtotal / diners
println("Subtotal ₹$subtotal split $diners ways is ₹$perHead each")
}
$ kotlinc 05_conversions_and_input.kt -include-runtime -d 05.jar
$ printf '2400\n4\n' | java -jar 05.jar
Enter the subtotal in rupees:
Enter the number of diners:
Subtotal ₹2400.0 split 4 ways is ₹600.0 each
(Piping input with printf '2400\n4\n' | is how this README feeds the program two lines without
you typing them by hand to reproduce the transcript; typing them directly at a real terminal after
running java -jar 05.jar works exactly the same way.)
A plain readLine() (capital L, no n) also exists, and it's the one older Kotlin material and
search results still show — this course deliberately doesn't use it:
$ kotlinc OldStyle.kt -d out
OldStyle.kt:3:24: warning: 'fun readLine(): String?' is deprecated. Use `readln()` instead of `readLine()!!`, and `readlnOrNull()` instead of `readLine()`.
val subtotalLine = readLine()!!
^^^^^^^^
readLine() returns String? (nullable — "maybe there's a line, maybe there isn't," for example
at end-of-input), which used to force readLine()!! just to get a plain String back. readln()
(added in Kotlin 1.6) does that job without the nullable type or the !! — the compiler's own
deprecation warning above says exactly that, and is why this course uses readln() from here on.
Bad numeric input still throws, as section 6 showed — readln() fixes the nullability problem,
not the "what if the text isn't a number" one.
Full program: examples/05_conversions_and_input.kt.
Done here? The practice set for Part 2 — including the solutions — is on the part page.