Search code examples
reflectionkotlinkotlin-null-safety

How to get class of Any? variable in Kotlin?


I want my equals to compare class too and I wrote

    override fun equals(other: Any?): Boolean {
        return this::class == other::class && ...

    }

unfortunately it swears

Expression in a class literal has a nullable type 'Any?', use !! to make the type non-nullable

But I want to compare with nulls too. What about glorious "null safety"? They forgot it for reflection? I didn't find ?:: operator or something.


Solution

  • Think about this. The class is actually not different between a String and a String?, it's only the type that differs. You cannot invoke that operator on nullable types since it could mean you invoke it on null which would lead to a NullPointerException:

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

    With the help of the scope function let you can ensure it isn't null and use the class literal syntax:

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

    The Elvis operator ?: is used to handle the null case by making the expression false (not equal).