关于继承:如何在Scala中正确设置从另一个继承的类?

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

我一直在看在线示例和教程,但找不到任何能解释这种(继承性)与java的区别的内容。简单示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Shape {
String type;
Shape(String type) {
    this.type = type;
  }
...
}

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

在上面的示例中,令我感到困惑的是,我需要调用超类来设置\\'type \\'变量,并通过访问它来告诉我Box对象的类型。在Scala中,该怎么做?我知道scala也使用traits接口,但是上述示例是否从scala中完全省略了?任何人都可以引导我举一个好例子或对其进行解释。我真的很感激。


您可以在Scala中编写几乎完全相同的东西,更加简洁:

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

在第一行中,type之前是var的事实使编译器添加getter和setter(来自规范中的" 5.3类定义"):

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.

在第二行中,name之前没有valvar,因此只是一个构造函数参数,在这种情况下,我们将在extends子句中传递给超类构造函数。没有为name添加任何getter或setter,因此,如果我们创建了square的实例square并称为square.name,则它将不会编译。

还要注意,type是Scala中的关键字,因此在上面的定义和示例中,我都必须用反引号将其包围:

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

您可以阅读许多资源,以获取有关Scala中继承的更多信息。例如,请参见《 Scala编程》的第4章和第5章。