https://kotlinlang.org logo
x

xii

02/24/2021, 10:57 AM
Is there any way to be able to pass a condition based on a data class property as parameter? (thread)
Maybe I'm overthinking this, but I thought it would be neat: I have a method which, in a step, does this:
Copy code
val test = elements.findLast { it.isCondition }
my idea is to make it.isCondition to be passed by parameter, so it could be it.isConditionB based on an argument
but i'm not sure how to achieve it
maybe passing a function as argument?
y

Youssef Shoaib [MOD]

02/24/2021, 11:10 AM
You can either pass in a property reference that returns a boolean like this:
KProperty<Boolean>
or alternatively you can pass in a transformation function that takes an element of your type and spits out a boolean
x

xii

02/24/2021, 11:18 AM
i tried passing a function as you mentioned, but i get
Copy code
Expression '' of type 'Function<Boolean>' cannot be invoked as a function. The function 'invoke()' is not found
y

Youssef Shoaib [MOD]

02/24/2021, 11:33 AM
Have it as `transformer: (ItemType) -> Boolean
x

xii

02/25/2021, 6:28 PM
sorry i couldnt respond any more yesterday
that syntax doesnt work for me, but simply changing the parameter declaration to (itemType) -> Boolean instead of Function<Boolean> worked
thank you 🙂
2 Views