reflection - why SomeClass::class is KClass<SomeClass> but this::class is KClass<out SomeClass> -
i want print values of properties of class.
fun print() { val cl = this::class cl.declaredmemberproperties.filter {it.visibility != kvisibility.private}.foreach { println("${it.name} = ${it.get(this)}") } }
when try build code compiler error:
error:(34, 40) kotlin: out-projected type 'kproperty1<out someclass, any?>' prohibits use of 'public abstract fun get(receiver: t): r defined in kotlin.reflect.kproperty1'
when change this
class name someclass
fine
fun print() { val cl = someclass::class cl.declaredmemberproperties.filter {it.visibility != kvisibility.private}.foreach { println("${it.name} = ${it.get(this)}") } }
so problem compiler changers type of this::class
kclass<out someclass>
instead of using kclass<someclass>
. idea why happen?
the reason difference that, when use someclass::class
reference, sure class token representing someclass
, not 1 of possible derived classes, therefore kclass<someclass>
without type projections.
but this::class
written in function of open
or abstract
class or extension function can return class token of derived class, therefore, ensure type safety, type out
-projected: kclass<out someclass>
means actual type argument can someclass
or subtype.
example:
open class { fun f() { println(this::class) // kclass<out a> because can kclass<b> } } class b : a() b().f()
Comments
Post a Comment