[英]Scala: How to make a protected method accessible to sub-classes (on other instances)?
I'm trying to do something like this: 我正在尝试做这样的事情:
trait A[Out] {
protected def foo(): Out
}
trait B extends A[Int]
class WrapperB(b: B) extends B {
override protected def foo(): Int = b.foo() + 1
}
This won't compile, as WrapperB
has no access to b.foo()
. 这将无法编译,因为WrapperB
无法访问b.foo()
。
There are a few ways to resolve this, but these won't work for me: 有几种方法可以解决这个问题,但这些方法对我不起作用:
foo
public: won't work, because I want it to stay protected
. 让foo
公开:不会工作,因为我希望它保持protected
。 B
s in different packages. 使用包范围:不起作用,因为我打算在不同的包中有很多B
Is there any other way? 还有其他方法吗?
How about: 怎么样:
trait A[Out] {
protected def foo(): Out
}
trait B extends A[Int] {
protected def gimme(that: B) = that.foo()
}
class WrapperB(b: B) extends B {
override protected def foo(): Int = gimme(b) + 1
}
I have never liked the idea that private
and protected
can access other value's methods, I think it's bad design. 我从来不喜欢private
和protected
可以访问其他价值方法的想法,我认为这是糟糕的设计。 private
should mean private[this]
. private
应该是private[this]
。 If you need cross-value access, I think you should declare private[my-package]
, even if it means choosing a common base package in your case. 如果您需要跨值访问,我认为您应该声明private[my-package]
,即使这意味着在您的情况下选择一个公共基本包。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.