这里需要直接引用超类的setter/getter。通常你应该写这样的东西:
class SubFoo(n: String) extends SuperFoo(n) {
val lock = new ReentrantLock
override def name(): String =
{
lock.lock
try {
super.name()
} finally {
lock.unlock
}
}
override def name_=(arg: String): Unit = {
lock.lock
try {
super.name_=(arg)
} finally {
lock.unlock
}
}
}
但是,如果 setter 编译没有任何问题,getter 则不会,因为编译器会将其视为super.name.apply()
(字符串可以通过隐式转换获得此方法)。
我看到几个选项:
- 喜欢组合而不是继承(经典)。
- 更改变量名,使其私有并在超类中写入访问器(见下文)。
- 诉诸反射/手动名称 umangling voodoo。
我会选择选项 #1,但这里是选项 #2 的代码:
class SuperFoo( private var nameVar: String) {
def name: String = nameVar
def name_=(arg: String): Unit = nameVar = arg
}
class SubFoo(n: String) extends SuperFoo(n) {
val lock = new ReentrantLock
override def name(): String =
{
lock.lock
try {
super.name
} finally {
lock.unlock
}
}
override def name_=(arg: String): Unit = {
lock.lock
try {
super.name = arg
} finally {
lock.unlock
}
}
}
编辑:这是选项#1的可行实现:
trait Foo {
def name: String
def name_=(arg: String): Unit
}
class SimpleFoo( var name: String) extends Foo
class LockedFoo(foo: Foo) extends Foo {
val lock = new ReentrantLock
def name(): String =
{
lock.lock
try {
foo.name
} finally {
lock.unlock
}
}
def name_=(arg: String): Unit = {
lock.lock
try {
foo.name = arg
} finally {
lock.unlock
}
}
}