问题
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