gpt4 book ai didi

Scala:使用伴随对象的父对象的 protected 方法

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

我有一组类在类层次结构中管理数据库存储,如下所述,并且希望案例类能够访问伴随对象的父类中的 protected 方法:

class TableBase[T] { 
protected def insert(...):T {...}
protected def update(...) {...}
// Other "raw" CRUD-methods that I don't want the
// world to have access to
}

object User extends TableBase[User] {
}

case class User(id:Int, email:String) {
// But here it would be really useful to access the "raw" CRUD methods:
def changeEmail(newEmail:String) = User.update(...)
}

唯一的问题是在 User.changeEmail 中对 User.update 的调用是非法的,因为 User(类)不在 TableBase 的继承链中:

method update in class TableBase cannot be accessed in object models.User 
Access to protected method update not permitted because enclosing class
class User in package models is not a subclass of class TableBase in package
models where target is defined

是否有一种(方便的)方式允许这种类型的调用?

现在我必须将 changeEmail 类型的函数移到单例中,这使得调用代码相当冗长,或者复制方法签名。

最佳答案

我刚刚意识到一个可能的解决方案是将 User 和 TableBase 之间的“is-a”关系切换为“has-a”关系,如下所示:

class TableBase[T] { 
def insert(...):T {...}
def update(...) {...}
}

object User {
private val db = new TableBase[User]
}

case class User(id:Int, email:String) {
def changeEmail(newEmail:String) = User.db.update(...)
}

我希望能够在 User 中自定义 TableBase 的某些方面,但实际上这仍然是可能的,并且通过以下操作非常容易:

object User { 
private val db = new TableBase[User] {
// Override stuff here
}
}

实际上,这比我最初的解决方案要好得多,并且避免了方法上的命名冲突(即,有理由对 User 进行公共(public)“插入”,最好不要让它导致部分 protected 重载)。

关于Scala:使用伴随对象的父对象的 protected 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12291566/

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