I have a
class Foo {
lateinit var property1: String
lateinit var property2: Int
lateinit var property3: Long
}
Then is it possible to pass a property of the class in a function like this one?
fun bar(fooProperty: FooProperty) {
println(
when(fooProperty) {
Foo.property1 -> "Property1"
Foo.property2 -> "Property2"
Foo.property3 -> "Property3"
}
)
}
This is invalid code however. I was just wondering if that is achievable.
Yes, this is possible, just use ClassName::propertyName to get a reference to the property and KProperty1<ClassName, *> as the parameter type.
So, a full working example with your example class (changed a bit to make the class compile) would look like:
import kotlin.reflect.KProperty1
class Foo {
lateinit var property1: String
var property2: Int = 0
var property3: Long = 0
}
fun bar(fooProperty: KProperty1<Foo, *>) {
println(
when(fooProperty) {
Foo::property1 -> "Property1"
Foo::property2 -> "Property2"
Foo::property3 -> "Property3"
else -> throw IllegalArgumentException("Not a known property")
}
)
}
fun main() {
bar(Foo::property2)
}
This prints
Property2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With