kotlin - 如何使用 equals() 和 contains() 检查可为空类型的数据?我想它们都是字符串的方法,但为什么它们的行为不同?

标签 kotlin null nullsafe

情况一:可以编译运行。为什么 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")
equalsAny 声明了函数,不是 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/

相关文章:

android - Kotlin 如何调用扩展函数

URL 上的 Swift Nil 异常

java - 为什么 null 安全很重要

kotlin - 在Kotlin `when`语句(或其他分支构造)中将函数或lambda作为条件包括在内的最简洁方法是什么?

java - Appnext kotlin 集成

java - 未初始化的对象不为 null 并且在构造函数中返回

ruby-on-rails - SQLite3::ConstraintException: NOT NULL 约束失败: items.title: INSERT INTO "items"("image", "created_at", "updated_at") VALUES (?, ?, ?)

php - 为什么我得到 Undefined property: stdClass::with php 8 nullsafe operator

kotlin - 如何从 kotlin 引用 bool java 类?