https://kotlinlang.org logo
#getting-started
Title
# getting-started
j

Justin Yue

05/24/2021, 11:48 PM
I'm starting off w/ Kotlin, and I was wondering for retrieving console input, is it preferable to use
readLine()
from the kotlin.io package or to use `Scanner(System.
in
)` from the java.io package? I think my personal preference is going the Java route because I feel that returning
String?
from
readLine()
is something I don't want to deal with. But maybe I'm not using Kotlin's null safety as much as I should be?
From reading the docs, I feel that it's better to use the Java scanner if I'm doing console input since the Kotlin way may be overkill w/ null safety. But since the Kotlin way can return null when reading file input, I think Kotlin's io is better here.
m

Matteo Mirk

05/25/2021, 8:02 AM
using Java Scanner you have to deal with the hasNext()/next() paradigm and exceptions, with readLine() just with a nullable type: there’s no match in code simplicity when using Kotlin stdlib. I suggest you read a little more about nullable types and don’t be scared by them, it’s a good feature 😉
for example
Copy code
readLine()?.let { println("a non null input: $it") }
j

Jiddles

05/25/2021, 1:20 PM
If Im not wrong, using stdlib makes cross platform easier?
m

Matteo Mirk

05/26/2021, 8:32 AM
Also that, yes. Not everything inside stdlib is MPP, but you can always check in the docs, they have related badges in the right corner. Anyway, readLine() is compatible with JVM and Native
j

Justin Yue

05/26/2021, 5:13 PM
Apologies for not answering sooner. I definitely agree readLine() with a nullable type is great. However, my understanding is that it doesn't return null unless it reaches the end of a file when reading a file?
m

Matteo Mirk

05/28/2021, 7:19 AM
Yes exactly, but only if you attach standard input stream to a file, otherwise it will read from the command line by default here are some examples: https://www.journaldev.com/19757/kotlin-print-println-readline-scanner-repl#using-readline
3 Views