Have you ever wondered how !
and +
operator works ?
Let's make your own !
Long exercise but I wanted to make sure to see several examples to get a good knowledge about Operators for you !
The first section ({...}
) is about traditional, easy operator such as +
and *
. In Scala, you can use pretty much any characters to create a method name so it is not too hard at this point. Sorry for the math about complex numbers !
Next we see weirder ones with backslash \
and one famous one, the combine operator : |+|
, present in many libraries such as Cats.
And finally even weirder ones. Operator that goes before the caller ! Those are called unary
and the syntax is :
class MyClass(...) {
// ... other fields and methods ...
def unary_[prefix_name] = ???
// ... more things ...
}
val a : MyClass = ???
[prefix_name] a
It is worth noting that only a selected list of characters and names are authorized for unary
methods. For example, +
, *
, ~
, and !
are allowed. You can find a lot of example of people using unary
on GitHub.