Thursday, October 15, 2009

Boolean.flip()

Recently I needed a Boolean in a groovy project I was working on to alternate back and forth (for row highlighting with Apache POI). I thought it would be slick to metaclass a flip() method (something I've always thought should be there) into Boolean. It turns out, this is not possible. I browsed the Java source and learned that all primitive wrapper classes are immutable. I'm not completely sure why they did this. My guess is to protect programmers from hurting themselves by mutating objects in a collection and possibly creating unexpected behavior or a race condition.  I could have created my own boolean wrapper class, of course, or use Apache Commons MutabeBoolean. In the end, I decided not to be fancy and just reference a new object like

Boolean foo = false
foo = !foo
But boy, it would have been pretty & nice to have
Boolean foo = true
foo.flip()