Andy
Andy

Reputation: 10830

How to properly set up a class that inherits from another in Scala?

I have been looking at examples online, and tutorials, and I cannot find anything that explains how this (inheritance) differs from java. Simple example:

class Shape {
String type;
Shape(String type) {
    this.type = type;
  }
...
}

class Square extends Shape {
Square(String name){ 
    Super(name);
  }
....
}

Whats confusing me is in the above example I need to call the super class in order to set the 'type' variable, as well as to access it to tell me the Box objects' type as well. In Scala, how can this be done? I know scala uses traits interfaces as well, but is the above example omitted completely from scala? Can anyone direct me to a good example or explain it. I really appreciate it.

Upvotes: 0

Views: 167

Answers (1)

Travis Brown
Travis Brown

Reputation: 139038

You can write almost exactly the same thing in Scala, much more concisely:

class Shape(var `type`: String)
class Square(name: String) extends Shape(name)

In the first line, the fact that type is preceded by var makes the compiler add getters and setters (from "5.3 Class Definitions" in the specification):

If a formal parameter declaration x : T is preceded by a val or var keyword, an accessor (getter) definition (§4.2) for this parameter is implicitly added to the class. The getter introduces a value member x of class c that is defined as an alias of the parameter. If the introducing keyword is var, a setter accessor x _= (§4.2) is also implicitly added to the class.

In the second line name is not preceded by val or var, and is therefore just a constructor parameter, which is this case we pass on to the superclass constructor in the extends clause. No getters or setters are added for name, so if we created an instance square of Square and called square.name, it wouldn't compile.

Note also that type is a keyword in Scala, so I've had to surround it by backticks in both the definition and the example above:

Example 1.1.2 Backquote-enclosed strings are a solution when one needs to access Java identifiers that are reserved words in Scala.

There are many, many resource that you can read for more information about inheritance in Scala. See for example Chapters 4 and 5 of Programming Scala.

Upvotes: 5

Related Questions