如何获得 Any 的 class? Kotlin 中的变量?
How to get class of Any? variable in Kotlin?
我希望我的 equals
也能与 class 进行比较,我写了
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
s 进行比较。光荣的"null safety"呢?他们忘记了反思?我没有找到 ?::
运算符或其他东西。
想想这个。 class其实和String
和String?
没有区别,只是类型不同而已。您不能在可空类型上调用该运算符,因为这可能意味着您在 null
上调用它会导致 NullPointerException
:
val x: String? = null
x!!::class //throws NPE
在范围函数 let
的帮助下,您可以确保它不是 null
并使用 class literal syntax:
return other?.let { this::class == other::class } ?: false
?:
用于通过使表达式 false
(不等于)来处理 null
的情况。
我希望我的 equals
也能与 class 进行比较,我写了
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
s 进行比较。光荣的"null safety"呢?他们忘记了反思?我没有找到 ?::
运算符或其他东西。
想想这个。 class其实和String
和String?
没有区别,只是类型不同而已。您不能在可空类型上调用该运算符,因为这可能意味着您在 null
上调用它会导致 NullPointerException
:
val x: String? = null
x!!::class //throws NPE
在范围函数 let
的帮助下,您可以确保它不是 null
并使用 class literal syntax:
return other?.let { this::class == other::class } ?: false
?:
用于通过使表达式 false
(不等于)来处理 null
的情况。