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
)

Leave a Reply

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