[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.

April 4, 2016

Related Posts

Leave a reply

This website stores some user agent data. These data are used to provide a more personalized experience and to track your whereabouts around our website in compliance with the European General Data Protection Regulation. If you decide to opt-out of any future tracking, a cookie will be set up in your browser to remember this choice for one year. I Agree, Deny