Superclass constructors in scala

Scala handling the constructor parameters of a superclass confuses me ...

using this code:

class ArrayElement(val contents: Array[String]) { ... } class LineElement(s: String) extends ArrayElement(Array(s)) { ... } 

It is announced that LineElement extends ArrayElement, it seems strange to me that the parameter Array(s) in ArrayElement(Array(s)) creates an instance of Array - runtime ??? Is this scala syntactic sugar or is something else happening here?

+4
source share
2 answers

Yes, the expression Array(s) is evaluated at runtime.

 class Foo (val x: Int) class Bar (x: Int, y: Int) extends Foo(x + y) 

Scala allows expressions in calls to the superclass constructor (similar to what Java does using super(...) ). These expressions are evaluated at runtime.

+9
source

In fact, Array(s) is evaluated at runtime because the structure you use is an efficient call to the main constructor of your superclass.

Recall that a class can only have a primary constructor that takes arguments in its definition of class A(param:AnyRef) , other constructors are called this and have the mandate to call the primary constructor (or bind constructors before it).

And such a restriction exists for super calls, i.e. the primary constructor of the subclass calls the super primary constructor.

Here's how to see such a Scala structure

 class Foo (val x: Int) class Bar (x: Int, y: Int) extends Foo(x + y) 

Java mapping

 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; } } 
+2
source

Source: https://habr.com/ru/post/1388113/


All Articles