Zorgan
Zorgan

Reputation: 9133

Where do void function/property calls execute to?

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

Answers (3)

Alexey Romanov
Alexey Romanov

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

lorraine batol
lorraine batol

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

Josh
Josh

Reputation: 500

What you're referring to is called dead code elimination. Here is one related post that addresses a similar question.

Upvotes: 0

Related Questions