0

I want to get the name of a parameter passed into a lambda expression in Kotlin. In C# I would use an Expression<Func<T, ...>> to get the parameter name, but I'm not sure whether this is possible in Kotlin

import java.util.*

fun main(args: Array<String>) {
    val foo = Foo<Model>()
    foo.bar { it.age }
    // Should print "age"
}

data class Model(val id: UUID, val name: String, val age: Int)

class Foo<T> {
    fun bar(expression: (x: T) -> Any) {
        println(/*The name of the parameter*/)
    }
}

Is this possible in Kotlin?

7
  • Do you mean you want to pass a property which name shall be printed? Since age does not function as a “parameter” here Commented Feb 16, 2018 at 11:28
  • @s1m0nw1 ...yes (I think?) Commented Feb 16, 2018 at 11:33
  • Try to pass a KProperty<*> directly (change parameter type) and use its name in bar. Passed as an argument like this: foo.bar(foo::age) Commented Feb 16, 2018 at 11:35
  • @s1m0nw1 not sure what you mean, would you mind providing an answer? Commented Feb 16, 2018 at 11:36
  • I did but can’t test it currently:[ Commented Feb 16, 2018 at 11:39

1 Answer 1

2

If you want to pass around properties and print their names, you can do it by using KProperty:

fun main(args: Array<String>) {
    val foo = Foo<Model>()
    foo.bar(Model::age)
}

class Foo<T> {
    fun bar(p: KProperty<*>) {
        println(p.name)
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

This almost works, except you can't pass foo::age because age is a property of Model
Model::age then? Well probably not what you want to achieve I’m afraid
Yes. It might not be exactly what I wanted, but it does the job!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.