Superclass constructors in scala
Asked Answered
W

2

6

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?

Waterloo answered 27/12, 2011 at 10:51 Comment(0)
W
10

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.

Weismannism answered 27/12, 2011 at 11:1 Comment(1)
I guess it is scala syntactic sugar then... things like: class LineElement(s: String) extends ArrayElement({ println(">> SubClass!"); Array(s)}) {...} is possibleWaterloo
V
2

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;
  }
}
Venereal answered 27/12, 2011 at 11:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.