Can a lambda store info like which property of a o...
# random
k
Can a lambda store info like which property of a object to use? For example I have a have a class
Person
with id and name Now I want to find the index of the person having id = 3 from a list of persons
Copy code
val pos = persons.imdexOf{ it.id == 3 }
But i just want to create something like
Copy code
persons.findPos(Person::id, 3)
How can i tell the compiler to use the id property?
g
Are you looking something like getter reference?
Copy code
Person.id::get
k
Exactly @gildor
Can you share how it would look in Kotlin
l
Something like
fun <T, R> Iterable<T>.findPos(valueExtractor: (T) -> R, input: R): Int
?
g
@kartikpatodi As I understand just now you are looking rather something like this: https://pl.kotl.in/ByNbMJrK4
example with getter (which I wrote in a wrong way) make sense if you need reference to getter of particular instance
Copy code
val getter: () -> Int = Person(1)::id::get`
k
@gildor isn't this using reflection?
@leolima Thanks your solution worked
g
No, it doesn't require full reflections
But usage of lambda is actually more flexible
And still very similar https://pl.kotl.in/BJxljJBtN
I just thought that property syntax was closer to your original example
k
Actually you can omit the
get
part and just use
Person::id
with the lambada approach
g
Ah, you right 👍