为什么我得到这个?Kotlin:类型不匹配:推断的类型是String?但是字符串是预期的 [英] Why do I get this? Kotlin: Type mismatch: inferred type is String? but String was expected

查看:87
本文介绍了为什么我得到这个?Kotlin:类型不匹配:推断的类型是String?但是字符串是预期的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试运行此代码时:

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]}")
    }
}

我得到此错误:(2,25)Kotlin:类型不匹配:推断的类型是String?但应该使用String.我该如何解决?

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

推荐答案

在Kotlin中,仅使用点运算符对可空类型调用函数是编译错误,因为它可能会导致空指针异常.为了避免此类错误,编译器会强制您检查引用是否不为null.也可以使用安全呼叫运营商?..我建议您阅读有关该主题的出色的Kotlin文档:零安全.

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.

如果您已开始使用Kotlin,我还建议您以更具声明性/实用性的方式开始编写代码.看看如何以一种更简单的方式完成您想要的事情:

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) }
}

这篇关于为什么我得到这个?Kotlin:类型不匹配:推断的类型是String?但是字符串是预期的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆