Marc Knaup
10/31/2017, 6:05 PMopen class Foo
class FooChild : Foo() {
val bar: Int = 42
}
fun invokeBar(foo: Foo): Any? {
val property = (foo::class as KClass<Foo>).declaredMemberProperties.find { it.name == "bar" }!!
return property.invoke(Foo())
}
fun main(args: Array<String>) {
println(invokeBar(FooChild()))
}
Would lead to
Exception in thread "main" java.lang.IllegalArgumentException: object is not an instance of declaring class
The out projection does make sense to ensure that you pass a receiver of the correct type.
Since the type of foo isn’t known at compile-time there’s no way the compiler can no the correct type and hence you have to make a cast.