Why does Kotlin compile `(Entity)->Boolean` to ...
# announcements
k
Why does Kotlin compile
(Entity)->Boolean
to just a
Function1<Entity, Boolean>
and not to something that doesn't require boxing like `Predicate<Entity`>?
j
That's not enough to tell the input type of the function. Maybe you meant
Predicate<Entity>
with the implied
Boolean
return.
k
Oof, yeah 🤦‍♂️ (Edited original msg)
j
You can always create your own:
Copy code
typealias Predicate<T> = (T) -> Boolean
k
No the issue is the boxing
j
Can't you inline your implementation of the predicate?
k
No
e
Compiling like that would have required a huge number of
FunctionXxx
interfaces to be included into the Kotlin standard library for all the combinations of pritimite types and still it would have been impossible to include all of them, but only a small subset. Better be pretictable here. In cases where you care avout boxing you can always define your own interface:
Copy code
interface Predicate<T> {
    operator fun invoke(t: T): Boolean
}
However, I highly recommend to carefully measure the performance benefit of any such change in your code first. It actually helps much less often than it might seem to.
j
According to the article below, you can avoid the cost of boxing by replacing your predicate with a local function (instead of using a lambda). It might meet your needs: https://medium.com/@BladeCoder/exploring-kotlins-hidden-costs-part-2-324a4a50b70