0
Type mismatch with readline
In my code below I create three Strings. Then I use readLine to assign values to them. But the last example fails. It say there is a type mismatch with String and String was expected. And this is what I don't understand. https://sololearn.com/compiler-playground/czatpms38ko8/?ref=app
3 Antworten
+ 3
readLine in Kotlin returns a nullable string
readLine():String?
because the input might be null.
so it is not type String but type String?. This is an additional safety guard so that readLine can handle null values. Thus your error message.
You can modify c to
var c: String?
you can also use ?: in readLine() to provide a default value if null.
var s = readLine()?:"sometext"
+ 3
fun main() {
var a : String
var b : String
var c : String?
var d : String
a = readLine()!! // works
b = readLine().toString() // works
c = readLine() // works now
d = readLine()?:"42"
println(a)
println(b)
println(c)
println(d)
}
+ 3
Kotlin is very strict in typing that String? And String aren't the same. In kotlinville, the former with the question mark is called the "nullable" and its the Union set of a string and null data type.
Now when dealing with nullable, extra conditions must be checked for both null and the real cases. The operator !, ?: !!, If-else, ternary can be used.
I've seen advanced kotliner using the let statement too. For example
readLine()?.let { println(it) }