Operator Overload

The last week I’ve been using Scala to work on a pet project of mine. It’s a relatively nice language, but one quirk (which I’ve also noticed in Haskell) is the extensive use of operator overloading.

For example, here’s a code completion pop-up:

I want to share a rule of thumb that’s useful for these situations:

  • Operators are functions
  • Functions should have useful names

If I’m operating on 2 integers, then +, *, /, etc. all have perfectly obvious interpretations. If I’m operating on a XML node then what do things like “/:\“, “\\“, and “\mean? And more importantly, is that meaning conveyed better then using an alternative such as ‘findAll’?

I hate to be curmudgeony, but there’s a point where I’d rather type ‘append’, then ‘+:=’.

4 Replies to “Operator Overload”

  1. Maybe your intellisense should be better. A single comment that descripes the acceptable operands and the opration would be more than enough to fix this situation.

    1. Sure, that’s a reasonable idea. Something that I would prefer (in cases where an operator is non-obvious) is to have a named method, and the operator for those who want to go that route.

      Normally I end up F3’ing into the source and poking around until I figure out what the intent of a method or operator is.

  2. Not Scala developer, but, operator overloading can be a litle mess in several programming languages. I met once a pascal compiler that explicitly allow declare an operation, both as a function, and an operator:

    integer function Add(x, y: integer); operator “+”;


    X1 := Y + Z;
    X2 := Add(X, Y);

    If you ever check operator overloading in C++, you’ll see its quite a mess.
    I wish that could be explicitly added to many programming languages.

    1. I agree, it’s the kind of thing that can be really handy in some cases, but at the same time, it’s very easy to overuse and end up with something opaque. Another example that I see everyday is how dependencies are specified in SBT:

      libraryDependencies ++= Seq(
        "junit" % "junit" % "4.10",
        "org.apache.hadoop" % "hadoop-core" % "1.0.2",
        "org.apache.lucene" % "lucene-core" % "3.5.0",
        "org.scalatest" %% "scalatest" % "1.7.2" % "test"

      It turns out ‘%’ and ‘%%’ mean different things (%% appends the Scala version for the package). I definitely would have been okay with writing ‘package(A, B, Version)’ here :).

Leave a Reply

Your email address will not be published. Required fields are marked *