[英]a confusion about calling super class method in scala
this is my Scala code, I will paste it first 这是我的Scala代码,我先粘贴它
abstract class Item {
def price(): Double
def descript(): String
}
class SimpleItem(var price: Double, var descript: String) extends Item
class Bundle(price: Double, descript: String, var other: Item)
extends SimpleItem(price, descript) {
override def price = other.price + super.price
override def descript = "this item can contain other item,and now it's containning:"+
other.descript
}
in method price of Bundle
, when I use super.price
, the compiler thinks I use the private attribute of the super class, but when I change it to super.price()
, now the compiler thinks I add ()
to Double
. 在
Bundle
方法价格中,当我使用super.price
,编译器认为我使用超类的私有属性,但当我将其更改为super.price()
,编译器认为我将()
添加到Double
。 Now I am confused: Is there another way to call super class's method? 现在我很困惑:还有另一种方法可以调用超类的方法吗?
The sad truth is that scala does not allow you to override the getter nor the setter of a var. 可悲的事实是scala不允许你覆盖getter和var的setter。 This conflicts with the uniform access principle (and contrasts with
val
s, which you can override) but you'll have to live with this restriction. 这与统一访问原则冲突(与
val
s形成对比,你可以覆盖),但你必须忍受这种限制。
A (somewhat ugly) work around is to define a getter and setter yourself, like this: 一个(有点难看)的工作是自己定义一个getter和setter,如下所示:
class SimpleItem(private var _price: Double, private var _descript: String) extends Item{
def price = _price
def price_=( value: Double ) { _price = value }
def descript = _descript
def descript_=( value: String ) { _descript = value }
}
SimpleItem
is still functionally equivalent to your orignal version, and you can now override the setters and getters (now your Bundle
class will compile fine as is). SimpleItem
仍然在功能上等同于你的SimpleItem
版本,你现在可以覆盖setter和getters(现在你的Bundle
类将按原样编译)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.