gpt4 book ai didi

scala - 简单的 Scala getter/setter 覆盖

转载 作者:行者123 更新时间:2023-12-04 04:18:11 24 4
gpt4 key购买 nike

假设我们有一个具有“名称”属性的类:

class SuperFoo(var name: String) 

如果我想覆盖它,例如在调用周围添加一些锁定:
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
}
}
}

以上会产生编译错误:
super may be not be used on variable name 

任何想法如何正确实现这一点? (即覆盖 getter 和 setter 以在它们周围添加锁定)。谢谢!

最佳答案

这里需要直接引用父类(super class)的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()。 (字符串可以通过隐式转换得到这个方法)。

我看到几个选项:
  • 喜欢组合而不是继承(经典)。
  • 更改变量名,使其私有(private)并在父类(super class)中写入访问器(见下文)。
  • 诉诸反射/手动名称 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
    }
    }
    }

    关于scala - 简单的 Scala getter/setter 覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14069465/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com