Why SomeClass :: class is KClass <SomeClass>, but this :: class is KClass <out SomeClass>

I want to print the property values ​​of my class.

fun print() {
    val cl = this::class
    cl.declaredMemberProperties.filter {it.visibility != KVisibility.PRIVATE}.forEach {
        println("${it.name} = ${it.get(this)}")
    }
}

When I try to create this code, I get a compiler error:

Error:(34, 40) Kotlin: Out-projected type 'KProperty1<out SomeClass, Any?>' prohibits the use of 'public abstract fun get(receiver: T): R defined in kotlin.reflect.KProperty1'

When I change thisto class name SomeClass, everything is fine

fun print() {
    val cl = SomeClass::class
    cl.declaredMemberProperties.filter {it.visibility != KVisibility.PRIVATE}.forEach {
        println("${it.name} = ${it.get(this)}")
    }
}

So the problem is that the type of compiler change from this::classto KClass<out SomeClass>instead of using KClass<SomeClass>. Any idea why this is happening?

+6
source share
1 answer

, SomeClass::class , SomeClass, , KClass<SomeClass> .

this::class, open abstract , , type out -projected: KClass<out SomeClass> , SomeClass .

:

open class A {
    fun f() {
        println(this::class) // KClass<out A> because it can be KClass<B>
    }
}

class B : A()

B().f()
+7

Source: https://habr.com/ru/post/1016110/


All Articles