Reputation: 4381
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?
Upvotes: 7
Views: 7325
Reputation: 4345
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;
}
}
Upvotes: 2
Reputation: 31053
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.
Upvotes: 11