[Scala] Be aware of forEach evaluation

If you use Scala be aware of short circuit evaluation.

Since C/C++/Java are not that kind of functional you cant get into trouble with function parameters, which are only evaluated once.

Consider something like this:

thowExceptionWithParam will throw a RuntimeException
thowExceptionWithImplicit wont
thowExceptionWithParamImplicit wont
(throw new RuntimeException) will throw a RuntimeException

But why?
first it looks weird, but if you think about short circuit evaluation of boolean operations in non-functional language this does totally make sense. Scala does evaluate the expression once, before starting to iterate.

So if the “expression” can be evaluated it will be evaluated, even if your iterator is empty.

3.00 avg. rating (76% score) - 1 vote

Related Posts

Leave a reply