Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: invoking superclass constructor

Tags:

scala

I am experiencing a weird behavior by Scala handling of superclass constructors.

I have a really simple class defined in the following way

package server

class Content(identifier:String,content:String){
    def getIdentifier() : String    = {identifier}
    def getContent()    : String    = {content}
}

and a simple subclass

package server

class SubContent(identifier:String, content:String) extends Content(identifier, content+"XXX")){

    override def getContent():String = {
        println(content)
        super.getContent
    }
}

What's really strange is that in the subclass there are duplicates of the superclass attributes, so if i create a new object

var c = new SubContent("x","x")

the execution of

c.getContent

first prints out "x" (The valued provided to the subclass constructor), but returns "xXXX" (The value provided to the superclass constructor).

Is there any way to avoid this behavior? Basically what I'd like to have is that the subclass does not create its own attributes but rather just passes the parameters to the superclass.

like image 833
mariosangiorgio Avatar asked Sep 03 '10 17:09

mariosangiorgio


1 Answers

It's doing exactly what you told it to do. You augmented the 2nd constructor parameter when passing it on to the superclass constructor and then you used the superclass' getContent to provide the value returned from the subclass' getContent.

The thing you need to be aware of is that constructor parameters (those not tied to properties because they're part of a case class or because they were declared with the val keyword) are in scope throughout the class body. The class' constructor is that part of its body that is outside any method. So references to constructor parameters in method bodies forces the constructor parameter to be stored in a field so it can have the necessary extent. Note that your println call in getContent is causing such a hidden constructor parameter field in this case.

Replying to comment "Is there an alternative way to define it in order to avoid this? Or at least, if I never refer to the parameters of the subclass constructors their fields will be allocated (Wasting memory)?":

If the only references to plain constructor parameters (*) is in the constructor proper (i.e., outside any method body, and val and var initializers don't qualify as method bodies) then no invisible field will be created to hold the constructor parameter.

However, If there's more you're trying to "avoid" than these invisible fields, I don't understand what you're asking.

(*) By "plain constructor parameters" I mean those not part of a case class and not bearing the val keyword.

like image 176
Randall Schulz Avatar answered Oct 18 '22 02:10

Randall Schulz