Why do I get this? Kotlin: Type mismatch: inferred type is String? but String was expected

孤者浪人 提交于 2021-01-04 05:38:10

问题


When I try to run this code:

fun main() {
    val input: String = readLine()
    val outputs = input.toCharArray()
    for (i in 0 until input.length) {
        print("${outputs[i]}${outputs[i]}")
    }
}

I get this Error:(2, 25) Kotlin: Type mismatch: inferred type is String? but String was expected. How do I fix that?


回答1:


The readLine() function returns a String? (nullable String).

Return the line read or null if the input stream is redirected to a file and the end of file has been reached.

There is no end of File in the console inputs so there's no need to worry about nulls. You can use the unsafe call operator !! to cast it to a non null value String.

val input: String = readLine()!!



回答2:


In Kotlin, calling a function on a nullable type using only the dot operator is a compilation error as it could cause a null pointer exception. In order to avoid this kind of error, the compiler forces you to check if your reference is not null. It is also possible to use the safe call operator ?.. I recommend you to read the excellent Kotlin documentation about the subject: Null Safety.

If you have started using Kotlin, I also recommend you to start writing your code in a more declarative/functional way. Look how it is possible to accomplish what you want in a much simpler way:

fun main() {
    val input = readLine()
    input?.toCharArray()?.forEach { print(it) }
}



回答3:


in Kotlin ? means that the the variable can have null values
as readLine() can return null you get the error
try this code:

fun main() {
    val input: String? = readLine()
    input?.let {
    val outputs = it.toCharArray()
        for (i in 0 until it.length) {
            print("${outputs[i]}${outputs[i]}")
        }
    } ?: run {
        print("input was null")
    }
}


来源:https://stackoverflow.com/questions/62197209/why-do-i-get-this-kotlin-type-mismatch-inferred-type-is-string-but-string-wa

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!