情况一:可以编译运行。为什么 null 调用 equals() 时没有异常(exception)?
var myStr:String? = null
if (myStr.equals("hello"))
println("equals hello")
else
println("not equals hello")
情况2:无法编译。我想它与上述情况类似,但我错了。为什么?var myStr:String? = null
if (myStr.contains("hello"))
println("contains hello")
else
println("not contains hello")
最佳答案
equals
在可为空的字符串上工作,只是因为它是一个非常特殊的情况。有一个 equals
专为 String?
撰写.
fun String?.equals(
other: String?,
ignoreCase: Boolean = false
): Boolean
这不适用于 Int?
, 例如:var i: Int? = null
if (i.equals(1)) // error here
println("equals 1")
else
println("not equals 1")
equals
为 Any
声明了函数,不是 Any?
,所以通常不能在可为空的类型上调用它。无论如何,比较相等性的惯用方法是使用
a == b
,转换为 a?.equals(b) ?: (b === null)
对于可为空的 a
.也没有理由允许
myStr.contains("hello")
编译,因为 contains
在不可为空的 CharSequence
上声明.operator fun CharSequence.contains(
other: CharSequence,
ignoreCase: Boolean = false
): Boolean
你可以像这样检查它,使用可空链接:if (myStr?.contains("hello") == true)
关于kotlin - 如何使用 equals() 和 contains() 检查可为空类型的数据?我想它们都是字符串的方法,但为什么它们的行为不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68109865/