为什么 ”!!”将 readline 字符串值转换为 int 时需要

Why "!!" is required when converting the readline string value into int

我是kotlin新手,一直在研究这门语言的语法。据我了解,在 kotlin 中,您可以使用集成函数转换数据类型,例如:

.toInt() 

将 3.14 转换为整数:

3.14.toInt()

因为已知 readline() 函数 returns 一个字符串,我不确定为什么这个语法是正确的:

fun main() {
    println("please enter a int:")
    val num1 = readLine()!!.toInt()
    println("one more")
    val num2 = readLine()!!.toInt()

    println("sum : ${num1 + num2}")
}

此语法不正确

fun main() {
    println("please enter a int:")
    val num1 = readLine().toInt()
    println("one more")
    val num2 = readLine().toInt()

    println("sum : ${num1 + num2}")
}

returns错误:

 Error:(5, 26) Kotlin: Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type String

只是想寻找更多关于转换的解释以及 readline() 函数和类似函数的语法差异。

方法 readLine() returns a String? - 问号表示它可以是 nullString。在 Kotlin 中,当您在该实例上调用方法时,您需要使用 ?!! 处理具有可空类型的实例。

区别在于?只在实例不为null时才进行,而!!强制进行。后者可能会给你一个 NullPointerException.

例如:

val num1 = readLine()?.toInt()
// Here, num1 could either be a String or null

val num1 = readLine()!!.toInt()
// if it goes to this next line, num1 is not null. Otherwise throws NullPointerException

readLine() returns 字符串? (字符串的可空版本?) 函数 toInt() 接收 String(不可空类型)。

fun String.toInt(): Int   // non-nullable
fun String?.toInt(): Int  // nullable (call)

您必须进行某种类型的 null 检查以确保 toInt 将调用不可为 null 的对象。这 !!运算符转换可为空的字符串?类型为不可为 null 的字符串。