Another Tour of Scala


The Gist

Scala Operators shows a very short example of creating “operator-like” method calls.

My Interpretation

A method that takes one parameter can be used as if it were an operator, which is to say, without a dot or parenthesis.

Suppose you want to use Ruby’s <=> operator as a sorting mechanism.

Since Scala has very liberal rules about what can be in an identifier, you can make a method called <=> and it works just fine. The function we pass to sort function could also be written like so:

(a,b) => a.<=>(b)

A few caveats, however. For some reason, if your method ends in a colon, it is applied to the identifer to its right, not its left.

def :::: (other:Person) = other.age
def foo  (other:Person) = other.age
println(dave :::: rudy) // prints dave’s age
println(dave foo rudy)  // prints rudy’s age

Also, for some reason, if you wish to create a method that looks like an assignment, you must use an underscore:

def age_=(newAge:Int)
foo.age = 45

My Thoughts on this Feature

The colon and underscore stuff is seemingly random. I guess there’s some math mumbo jumbo that says

element :: list # puts element onto the front of list

and so that’s why that’s there. Subtle. As for the _= stuff, I’m at a loss; Ruby seems to be able to handle this more clearly, so it’s anyone’s guess.

Overall though, I guess this is all handy for creating DSLs. Seems odd, though, that we still need parens around expressions in if statements.