Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to pass class properties as function parameters in Kotlin?

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.

like image 951
Dj Sushi Avatar asked Oct 22 '25 07:10

Dj Sushi


1 Answers

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
like image 196
Ryan M Avatar answered Oct 24 '25 15:10

Ryan M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!