Scala's handling of superclass constructor parameters is confusing me...
with this code:
class ArrayElement(val contents: Array[String]) {
...
}
class LineElement(s: String) extends ArrayElement(Array(s)) {
...
}
LineElement is declared to extend ArrayElement, it seems strange to me that the Array(s)
parameter in ArrayElement(Array(s))
is creating an Array instance - runtime??? Is this scala's syntatic sugar or is there something else going on here?
When you define a subclass in Scala, you control the superclass constructor that's called by its primary constructor when you define the extends portion of the subclass declaration.
The superclass constructor can be called from the first line of a subclass constructor by using the keyword super and passing appropriate parameters to set the private instance variables of the superclass.
Scala constructor is used for creating an instance of a class. There are two types of constructor in Scala – Primary and Auxiliary. Not a special method, a constructor is different in Scala than in Java constructors. The class' body is the primary constructor and the parameter list follows the class name.
Use of super() to access superclass constructor As we know, when an object of a class is created, its default constructor is automatically called. To explicitly call the superclass constructor from the subclass constructor, we use super() . It's a special form of the super keyword.
Yes, the Array(s)
expression is evaluated at run-time.
class Foo (val x: Int)
class Bar (x: Int, y: Int) extends Foo(x + y)
Scala allows expressions in the calls to a superclass' constructor (similar to what Java does with its use of super(...)
). These expressions are evaluated at run-time.
Actually The Array(s)
is evaluated at run-time because the structure you've used is an effective call to primary constructor of your super class.
To recall, a class can only have on primary constructor that takes arguments in its definition class A(param:AnyRef)
, other constructors are called this
and are mandate to call the primary constructor (or to chain constructors up to it).
And, such a constraint exists on super call, that is, a sub class primary constructor calls the super primary constructor.
Here is how to see such Scala structure
class Foo (val x: Int)
class Bar (x: Int, y: Int) extends Foo(x + y)
the Java counterpart
public class Foo {
private x:int;
public Foo(x:int) {
this.x = x;
}
public int getX() {
return x;
}
}
public class Bar {
private y:int;
public Bar(x:int, y:int) {
/**** here is when your array will be created *****/
super(x+y);
this.y = y;
}
public int getY() {
return y;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With