考虑这段代码(类型安全单位):
abstract class UnitsZone {
type ConcreteUnit <: AbstractUnit
abstract class AbstractUnit(val qty: Int) {
SOME_ABSTRACT_MEMBERS
def +(that: ConcreteUnit): ConcreteUnit = POINT_OF_INTEREST.apply(this.qty + that.qty)
def apply(param: Int) = SOME_IMPLEMENTATION
}
def apply(qty: Int): ConcreteUnit
}
object Imperial extends UnitsZone {
type ConcreteUnit = Pound
class Pound(override val qty: Int) extends AbstractUnit(qty) {
CONCRETE_MEMBERS_HERE
}
def apply(qty: Int) = new Pound(qty)
}
为了使整个事情有效,我需要调用外部对象的apply
方法继承(在上面的代码中标记为 POINT_OF_INTEREST )。考虑到这一点,我敢问几个问题:
答案 0 :(得分:7)
使用自我参考:
abstract class UnitsZone {
outer =>
type ConcreteUnit <: AbstractUnit
...
abstract class AbstractUnit(val qty: Int) {
def +(that: ConcreteUnit): ConcreteUnit = outer.apply(this.qty + that.qty)
...
}
}
有关此构造允许您执行的其他操作的详细信息,请参阅SO Scala教程的第17. Self references章。
答案 1 :(得分:4)
就像Java一样,
class Foo {
val foot = 0
class Bar {
val bart = Foo.this.foot
}
}
或以Scala方式,
class Foo { self =>
val foot = 0
class Bar {
val bart = self.foot
}
}