Johann Pardanaud
02/20/2023, 3:11 PMKProperty
?
For example, if I have:
class Foo(val bar: Bar)
class Bar()
val fooInstance = Foo(Bar())
val kprop = fooInstance::bar
The type of kprop
is KProperty0<Bar>
. How can I obtain a KClass<Bar>
from this property reflection? This would allow to reference some properties contained in the Bar
class, or even some deeply nested properties.
Basically, I’m trying to reproduce what a Key-Path expression does in Swift, but in a Kotlin way 🙂Sam
02/20/2023, 3:20 PMSam
02/20/2023, 3:22 PMFoo::bar.instanceParameter?.type
would get you the type of Foo
, but of course fooInstance::bar
doesn’t have an instance parameterephemient
02/20/2023, 3:23 PMJohann Pardanaud
02/20/2023, 3:48 PMSam
02/20/2023, 3:50 PMFoo::bar
, which is an unbound reference, that will work fine. From your original post it sounds like you want to pass fooInstance::bar
instead, which is what makes it tricky because that’s a bound reference and can’t (as far as I know) be converted to an unbound reference.Johann Pardanaud
02/20/2023, 3:51 PMFoo::bar
ephemient
02/20/2023, 3:52 PMclass Foo(val bar: Bar)
class Bar(val baz: Int)
operator fun <T, U, V> ((T) -> U).plus(then: (U) -> V): (T) -> V = {
then.invoke(this.invoke(it))
}
fun main() {
val fooInstance = Foo(Bar(0))
println((Foo::bar + Bar::baz)(fooInstance))
}
using unbound references, although I don't think that's very workable without supporting compiler plugins and libraries like Arrow OpticsSam
02/20/2023, 3:54 PMSam
02/20/2023, 3:56 PMJohann Pardanaud
02/20/2023, 4:00 PMDavid Kubecka
02/21/2023, 10:22 AM