Reputation: 9133
Here's code:
fun main(args: Array<String>){
val items = listOf(1, 2, 3, 4)
items.first()
items.last()
items.filter { it % 2 == 0 }
}
I have some extension methods like first()
and last()
- but they arn't doing anything (not being a assigned to a variable of anything). Does this mean the compiler just skips over them and doesn't do anything?
Upvotes: 0
Views: 44
Reputation: 170795
but they arn't doing anything (not being a assigned to a variable of anything)
So far as the compiler knows, they could have side-effects (e.g. printing something or setting a field) and in this case they'd have to be executed. If they were inline
, the compiler could maybe eliminate them as Josh's answer mentions, after inlining. But they aren't, so the compiler can't rely on their definitions (as opposed to signatures): at the runtime there could be a different JAR containing these methods and defining them with side effects.
But JIT will very likely inline them and then eliminate if you run this code enough time; just not immediately.
In principle there could be contracts declaring these methods to be pure and then the compiler could eliminate them. But current contracts don't support this, as far as I know.
Upvotes: 2
Reputation: 6281
The methods get called because you invoked it, but the results you didn't store in a reference variable, it would still be created on the heap if I'm not wrong (immediately eligible for garbage collection) but without a variable reference linked to it.
Upvotes: 1