如何获得任何类?科特林中的变量



我希望我的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进行比较。光荣的"零安全"呢?他们忘记了反思?我没有找到?::操作员或其他东西。

想想看。类实际上在StringString?之间没有区别,只是类型不同。您不能在可为空的类型上调用该运算符,因为这可能意味着您在null上调用它会导致NullPointerException

val x: String? = null
x!!::class //throws NPE

借助 scope 函数let您可以确保它不null并使用类文字语法:

return other?.let { this::class == other::class } ?: false

Elvis 运算符 ?: 用于通过使表达式false(不相等(来处理null情况。

最新更新