Following a discussion with a friend about operator overloading. I am looking at creative and/or useful example usage of operator overloading in Scala. I have some cool illustrations:
+ * -
)| > < >>
)|
)Have you other nice examples ?
The ones I don't mind using occasionally:
|>
(e.g., someValue |> println
):=
one some structures like observable value holders to mimic assignment<=>
(two-way), <==
(one-way) (e.g., field.enabled <=> options.isEditable
I find useful two "built-in" operators in Scala: ::
and ->
.
In maps creation, you can write Map("a" -> 1)
and Scala translates "a" -> 1
into ("a", 1)
tuple.
::
is used for appending in front of List, it's also very convenient.
Also +=
and -=
operators for collections are great, especially because they apply to mutable and immutable ones as well.
This is a bit a controversial topic in the scala community. One the one side people fear abuse could lead to incomprehensible programs. If you think seriously about it it already exists. Because what operators feel ‘naturally’? So lets take mathematical Operators: + - * / So why in ‘most’ programming languages + is defined on Strings ?
On the other side ‘well’ known operators could lead to more concise and comprehensible code. Scala supports unicode symbols so you could use symbols like /u+2211. Example: List(1,2,3).sum //would give us 6, using sum instead of /u+2211 because lacking unicode keyboard support.
So instead of 3 characters (s,u,m) we have one (/u+2211) Is this good or bad? In my opinion scala community will find a common sense on this topic but it will take some time.
Other programming languages which support unicode expressions include fortress.
A while ago I showed how to create a DSL with operators to manipulate the nodes and properties of a JCR tree. If laid out correctly the code resembles an ASCII art drawing of the actual content tree. The following Scala code
root ¦- "movies" -+ { n: Node =>
n ¦= ("title", "Night on Earth")
n ¦= ("length", 123L)
n ¦= ("ratings", 9L::8L::5L::Nil)
n ¦= ("languages", "en"::"it"::"fi"::"fr"::Nil)
n ¦- "cast" -+ { n: Node =>
n ¦= ("Gena Rowlands", "Victoria Snelling")
n ¦= ("Winona Ryder", "Corky")
n ¦= ("Roberto Benigni", "Taxi Driver") }}
is equivalent to this version in Java:
Node movies = root.addNode("movies");
movies.setProperty("title", "Night on Earth");
movies.setProperty("length", 123L);
movies.setProperty("ratings", new String[]{"9", "8", "5"}, PropertyType.LONG);
movies.setProperty("languages", new String[]{"en", "it", "fi", "fr"}, PropertyType.STRING);
Node cast = movies.addNode("cast");
cast.setProperty("Gena Rowlands", "Victoria Snelling");
cast.setProperty("Winona Ryder", "Corky");
cast.setProperty("Roberto Benigni", "Taxi Driver");
While not necessarily useful, it might deserve a point for creativity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With