Scala Constructor vs. Java Constructor

1. Constructor With Parameters

Java Code

1
2
3
4
5
6
public class Foo() {  
public Bar bar;
public Foo(Bar bar) {
this.bar = bar;
}
}

Scala Code

1
class Foo(val bar:Bar)

2. Constructor With Private Attribute

Java Code

1
2
3
4
5
6
public class Foo() {  
private final Bar bar;
public Foo(Bar bar) {
this.bar = bar;
}
}

Scala Code

1
class Foo(private val bar:Bar)

3. Call Super Constructor

Java Code

1
2
3
4
5
public class Foo() extends SuperFoo {  
public Foo(Bar bar) {
super(bar);
}
}

Scala Code

1
class Foo(bar:Bar) extends SuperFoo(bar) {}

4. Multiple Constructors

Java Code

1
2
3
4
5
6
7
8
9
public class Foo {  
public Bar bar;
public Foo() {
this(new Bar());
}
public Foo(Bar bar) {
this. bar = bar;
}
}

Scala Code

1
2
3
class Foo(val bar:Bar){  
def this() = this(new Bar)
}

5. Methods of getter and setter

Java Code

1
2
3
4
5
6
7
8
9
10
11
12
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;
}
}

1. Scala Code

1
2
import scala.reflect._  
class Foo(@BeanProperty var bar:Bar)

2. Scala Code

import scala.reflect._  
class Foo(aBar:Bar) {  
    @BeanProperty  
    private var bar = aBar  
}