https://kotlinlang.org logo
Title
v

Viet Hoang

02/12/2019, 1:46 AM
Hello, does anyone know the difference between
::class
and
.javaClass.kotlin
? And why is that in below example, the later declaration works but the prior doesn’t ?
class Test {
    fun testMethod() {
        this::class.memberProperties.forEach { println(it.get(this)) } // compile error 
        this.javaClass.kotlin.memberProperties.forEach { println(it.get(this)) }
    }
a

alex2069

02/12/2019, 1:58 AM
I can't tell you why it's like this, but:
this::class
is
KClass<out Test>
Whereas
this.javaClass.kotlin
is
KClass<Test>
And if you go down the chain and look at each type explicitly:
val k1: KClass<out Test> = this::class
val m1: Collection<KProperty1<out Test, *>> = k1.memberProperties
val p1: KProperty1<out Test, *> = m1.first()

val k2: KClass<Test> = this.javaClass.kotlin
val m2: Collection<KProperty1<Test, *>> = k2.memberProperties
val p2: KProperty1<Test, *> = m2.first()
I imagine it's because
this::class
could be this class or its inheritors
Having said that - if the class is final then I would expect
this::class
to be
KClass<Test>