Why doesn’t the Boolean class have methods like not, if?
If I have a long chain such as a.b.c.e.f.g which consumes multiple lines, and it evaluates to a Boolean, but I need the inverse, I have to go back to the beginning and insert !. or worse to wrap the whole multi-line expression in parens, prepend and if and append the consequent expression.
It would seem logical if I could just use a not and if method like:
a.b.c.d.e.f.g.if{ doThis}
or a.b.c.d.e.f.g.not.if{ doThis}
Sorry, I wasn’t clear. I should have said, that’s why I wasn’t sure if would fit your use case.
You have lots of Booleans. With that many, it might be better in a collection of some kind. That might not fit your case at all. A Seq[Boolean]( a, b, … ) or set might be better or perhaps worse. It depends on what you are trying to do. I was putting it out there for consideration.
Question: When I copy/pate the implicit classic RichBoolean into the IntelliJ worksheet, it works as expected. However, if I copy it into a scala file, it get the error. What do I need to do to make is useful and why?
Error:(29, 16) `implicit' modifier cannot be used for top-level objects
implicit class RichBoolean(val value: Boolean) extends AnyVal {
Implicit classes need to be wrapped in classes or objects (plain objects or package objects). That’s because implicit class RichBoolean(value: Boolean) is expanded to:
implicit def RichBoolean(value: Boolean) = new RichBoolean(value)
class RichBoolean(value: Boolean)
Boolean class does have a “not” method. It’s named unary_!. As syntactic sugar, methods named unary_!, unary_-, unary_+, or unary_~, can be invoked using the corresponding prefix operator. Conversely, in scala the 4 prefix operators are just syntactic sugar for methods of those names. There’s nothing stopping you from using the full method name as postfix. That said, of course true.unary_! doesn’t read that nice.
The answer to why Boolean does not have not and if methods?
It is always difficult to tell why something does not exist, unless you know of a specific effort and why it failed.
I would guess it was never introduced, because people are largely happy with the existing options !myBool and if(myBool) { … }. I would expect the existing options to be highly optimized by the compiler, so that alternatives would perform less well.
I don’t know the entire history of every possible change that did or didn’t make it into Scala, but I guess the most probable answer is: because nobody has cared enough to get those methods included in the std library.