我希望我的equals
也比较类,我写了
override fun equals(other: Any?): Boolean {
return this::class == other::class && ...
}
不幸的是它发誓
Expression in a class literal has a nullable type 'Any?', use !! to make the type non-nullable
但我也想与null
进行比较。光荣的"零安全"呢?他们忘记了反思?我没有找到?::
操作员或其他东西。
想想看。类实际上在String
和String?
之间没有区别,只是类型不同。您不能在可为空的类型上调用该运算符,因为这可能意味着您在null
上调用它会导致NullPointerException
:
val x: String? = null
x!!::class //throws NPE
借助 scope 函数let
您可以确保它不null
并使用类文字语法:
return other?.let { this::class == other::class } ?: false
Elvis 运算符 ?:
用于通过使表达式false
(不相等(来处理null
情况。