Home > Net >  Kotlin Flow Control - readln()!!.toInt()
Kotlin Flow Control - readln()!!.toInt()

Time:03-21

I started learning Kotlin a few days ago and I don't really understand why in this case you should use readln()!!.toInt(), from where the number is taken and to which "line" it refers.

fun main(args: Array) {

var number: Int
var sum = 0

for (i in 1..6) {
    print("Enter an integer: ")
    number = readln()!!.toInt()

It would be extremely helpful if someone could explain that. Thank you!

CodePudding user response:

readline() (not readln()) returns a line from the standard input stream, or null if the input stream has been redirected to a file and EOF (end of file) is reached. Its return type is String? meaning it could either be a String, or it could be null.

!! is "We are sure this will never be null; force this into a non-nullable type." It means you don't have to deal with the condition where the object you're working with is null.

In this case, the !! is saying "We're sure that system input hasn't been redirected to a file (or if it has, that EOF hasn't been reached); wait for the user to input something."

It looks like someone has mixed up readline() and readln() (which I did when I first answered this question) - @Tenfour04 is right; there's no need to use !! with readln. It does the same thing, except it throws an exception if EOF is encountered.

  • Related