Code Monkeyism

the blog for developers

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.

scala
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
    public class Foo() {
       public Bar bar;
    
       public Foo(Bar bar) {
           this.bar = bar;
       }
    }
    

    Looks in Scala like this:

    class Foo(val bar:Bar)
    

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

  2. How to have private fields
    public class Foo() {
       private final Bar bar;
    
       public Foo(Bar bar) {
           this.bar = bar;
       }
    }
    

    Looks in Scala like this:

    class Foo(private val bar: Bar)
    

    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() ?
    public class Foo() extends SuperFoo {
       public Foo(Bar bar) {
          super(bar);
       }
    }
    

    Looks in Scala like this:

    class Foo(bar:Bar) extends SuperFoo(bar)
    
  4. How to have more than one constructor?
    public class Foo {
        public Bar bar;
    
        public Foo() {
           this(new Bar());
        }
    
        public Foo(Bar bar) {
    	   this. bar = bar;
        }
    }
    

    Looks in Scala like this:

    class Foo(val bar:Bar) {
      def this() = this(new Bar)
    }
    
  5. Secondary constructors like this() need to delegate to another constructor to work (Thanks @Synesso).

  6. How to get bean style setters and getters?
     public class Foo() {
       private Bar bar;
    
       public Foo(Bar bar) {
           this.bar = bar;
       }
    
       public Bar getBar() {
          return bar;
       }
       public void setBar(Bar bar) {
          this.bar = bar;
       }
    }
    

    Looks in Scala like this:

    class Foo(@BeanProperty var bar:Bar)
    

    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:

    class Foo(aBar:Bar) {
        @BeanProperty
        private var bar = aBar
    }
    

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.

Guide to CodeMonkeyism

Over the last 4 years I wrote many articles on this blog. To make it easier for you to find the relevant ones, I've organized them into topics.

Top 10

6 reasons why my VC funded startup did fail

Go Ahead: Next Generation Java Programming Style

Java Interview questions: Write a String Reverser

The dark side of NoSQL

7 Bad Signs not to Work for a Software Company or Startup

Is Java dead?

Scala vs. Clojure

Never, never, never use String in Java

No future for functional programming in 2008 – Scala, F# and Nu

Clojure vs Scala, Part 2

Java Developer

Is Java Dead?

Go Ahead: Next Generation Java Programming Style

Be careful with magical code

All variables in Java must be final

Never, never, never use String in Java

Bending Java: More readable code with methods that do nothing?

NoSQL Guy

NoSQL: The Dawn of Polyglot Persistence

The dark side of NoSQL

Essential storage tradeoff: Simple Reads vs. Simple Writes

Sharding destroys the goals of your relational database

The unholy legacy of databases

Startup/CTO

Development Dream Teams

6 reasons why my VC funded startup did fail

American vs. European style of Software Development

12 Things to Reduce Your Lead Time and Time to Market

The high cost of overhead when working in parallel

Essential storage tradeoff: Simple Reads vs. Simple Writes

Job Seeker

Another Good (Java) Interview Question

7 Bad Signs not to Work for a Software Company or Startup

Java Interview questions: Write a String Reverser (and use Recursion!)

Java Interview questions: Multiple Inheritance

As a Manager: What I value in developers

Top 10 Tips (+1) to Get a Pay Raise

Agilist

What Developers Need to Know About Agile

5 Practices Better to Change in Your Scrum Implementation

Scrum is not about engineering practices

ScrumMaster and ZenMaster: The joke of certification

What is Trans-Scrum?