I'm doing beginner level Kotlin and I'm trying to do a multi line input and I found this code:
var originalTexts: MutableList<String> = mutableListOf()
while (true) {
val originalText = readLine()
if (originalText == null) break
originalTexts.add(originalText)
}
The problem is I dont know how to input null or EOF in the input stream in console using readLine(). I tried ctrl+z or ctrl+d but is not working. Beginner here please help guys.
Edit: I'm using Intellij in Windows OS
A null return from readLine()
indicates an end-of-file condition — basically, there can be no more input.
But whether and how that can happen depends on how you're running the program:
If you're running it in a terminal window, then you can signal end-of-file with a special key combination, which depends on the platform:
Ctrl
+ D
Ctrl
+ X
then Return
If you're running it with the input redirected from a file (eg by appending <filename
to the command), then you'll get an end-of-file condition after reading all the content of the file.
Some IDEs may provide their own combinations. For example:
Some IDEs may provide no way at all.
Some IDEs (eg online) don't support user input, and so readLine()
will always return null.
Due to the confusion that this can cause, Kotlin 1.6 added a readln()
function, which never returns null: instead, it throws a RuntimeException
if end-of-file is reached, or on platforms such as Kotlin/JS which don't support user input in this way.
(That may make it slightly easier to write beginner programs, but IMHO it's merely turning a compile-time issue into a hidden run-time one, which seems like a backward step for a language as clear and safe as Kotlin…)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.