mardi 28 mars 2017

why SomeClass::class is KClass

I want to print values of properties 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 build this code I get 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 this to 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 compiler changers type of this::class to KClass<out SomeClass> instead of using KClass<SomeClass>. Any idea why does it happen?





Aucun commentaire:

Enregistrer un commentaire