Fixing scala error with reduce: java.lang.UnsupportedOperationException: empty.reduceLeft

You may want to reduce a list of booleans with an “and” or an “or”:

List(true, false).reduce( 
  (x, y) => x && y
)

When you run this on an empty list, you’ll get this error:

java.lang.UnsupportedOperationException: empty.reduceLeft

To fix this, use foldLeft instead:

List(true, false).foldLeft(true)( 
  (x, y) => x && y
)

Interested in Scala? I send out weekly, personalized emails with articles and conference talks. Click here to see an example and subscribe.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *