Top 5 Things to Know About Constructors in Scala

I’ve been toying with Scala for some months now, one thing I’ve struggled with coming from Java are constructors in Scala. They are comparable to Java, but the syntax is different.

Creative Commons License credit: .Paolo.

To help get you going faster in Scala, the top 5 things to know about constructors. Here we go:

  1. How to do constructors with a parameter

    Looks in Scala like this:

    In this case val creates an immutable final public field, using var would create a mutable public field.

  2. How to have private fields

    Looks in Scala like this:

    Update: Changed due to comments. Thanks for the commentors to point this out

    Private fields are not as necessary as in Java, you can have public fields for attributes and change them to a method (def) later – without changing your clients.

  3. How to use super() ?

    Looks in Scala like this:

  4. How to have more than one constructor?

    Looks in Scala like this:

  5. Secondary constructors like this() need to delegate to another constructor to work (Thanks @Synesso).

  6. How to get bean style setters and getters?

    Looks in Scala like this:

    The attribute bar will still be public, which is not a big issue (see above) in Scala. But @BeanProperty helps when working with Java libraries and you need Bean conventions for the libraries to work.

    To add getBar and setBar but not a public field you need to:

Update: Changed to var, thanks to @eivindw.

Hope this helps you, if you have something to add, leave a comment. Should you struggle with the limited this() syntax (only one expression), then perhaps your constructors are doing too much. Consider the factory or better builder pattern instead.

Additional tip: use @Serializable to make your Scala classes serializable.

Nice coding in #Scala.

Comments are closed.