Search code examples
javalazy-evaluationlazy-initializationshort-circuiting

Is Java lazy when passing parameters to a method?


I am using this code:

A a = aMap.contains(key) ? aMap.get(key) : createAExpensively(key);

I believe that Java is lazy so if aMap.contains(key)) then the createAExpensively() function is never called.

Then, I stumbled onto the Map.getOrDefault() method. If we instead use:

A a = aMap.getOrDefault(key, createAExpensively(key));

is Java still lazy in calling the createAExpensively() function?

It seems that Java will first create the object A and pass it as a method parameter, based on this question, but I'm not totally sure.

If Java is not lazy when using Map.getOrDefault(), what is the point of that method?


Solution

  • Is Java still lazy in calling the createAExpensively() function? [in .getOrDefault(key, createAExpensively(key))]

    Function parameters are evaluated (from left to right) before actually calling the function. So createAExpensively(key) will be evaluated before calling getOrDefault. This behavior is also known as applicative order evaluation strategy.

    If Java is not lazy when using Map.getOrDefault(), what is the point of that method?

    It's useful when the default value is not expensive to create, for example when it's an already computed value or constant. In that case the Map.getOrDefault(...) call allows a more compact syntax than the ternary operator.

    If the default value is expensive to compute, and if you actually want to put the computed value in the map, then as of Java 8, you can use computeIfAbsent:

    A a = aMap.computeIfAbsent(key, k -> createAExpensively(k));