I'm starting off w/ Kotlin, and I was wondering fo...
# getting-started
j
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
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
If Im not wrong, using stdlib makes cross platform easier?
m
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
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
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