Init block for constructor body

Since I clicked the link before reading “See example 3”, I’m citing it here :slight_smile:

Here’s a simple method definition on a class. Works fine.

class Widget {
    def doTheThing() = 
        synchronized {
            ...
        }
}

Somebody makes a small change - adds a log line at the start of the method.

class Widget {
    def doTheThing() = 
        info("Doin' that sweet thing")
        synchronized {
            ...
        }
}

Jolly good, doesn’t get much simpler than that. I think most code reviewers would glaze over it in the middle of a big PR. The compiler (the best code reviewer) is also 100% happy with this change and raises no objections.
Bug

Three of Scala’s features come into play:

  1. Method bodies without { } brackets can only consist of a single expression
  2. Any statements or expressions in a class definition, outside of member definitions, become part > of the primary constructor.
  3. Member definitions and primary constructor content can intermingle with no ordering restrictions.

So the resulting code really acts like this:

class Widget {
    // executes within Widget constructor
    synchronized {
        ...
    }

    def doTheThing() = {
        info("Doin' that sweet thing")
    }
}

What was previously the body of the doTheThing method has been silently bumped into the body of the primary constructor. Oops!
[…] Example 3 would have been prevented if methods were simply required to have { }, or if primary constructor content was required to come before method definitions.

I think that the init block just makes things more clear and source code easier to read (in general).

1 Like