Is it possible to monkey-patch a new control structure in Scala? Basically I want to define a couple of control structures, such as the following unless method, and have them accessible anywhere in my project.
def unless(condition: => Boolean)(body: => Unit):Unit = if(!condition) body
You cannot monkey patch, which changes objects that already exist. However, you can write an implicit conversion that acts the same way (and is arguably safer) in most cases.
First of all, with
unlessas written, you don’t need it to be a method of every class. Just stick it in some object and import.But sometimes you do want it to act like a method on a class. For example, I often write
which could be more compactly written as a fold:
except that
Optiondoesn’t have fold. So I:(this is called the “pimp my library” pattern). Now I can use fold to my heart’s content, since any time there is an option and I call the
foldmethod, the compiler realizes that there is nofoldmethod and looks around for any way it can convert the class into something that does have afold. There is such a method, and the new class does to the existing option exactly what you would want from afoldmethod on the class itself.