scala 覆盖 protected 成员函数

标签 scala

我想实例化一个特征并覆盖 protected 函数 g,使其可访问(函数 f 用于测试)。

trait A {
    protected def g( i: Int ) = println( i )
    def f( i: Int ) = println( i )
}

我创建了一个对象 a1
val a1= new A {
    override def f( i: Int ) = super.f(i)
    override def g( i: Int ) = super.g(i)
    def h( i: Int ) = super.g(i)
}

并试图调用这些方法
a1.f(1)
a1.g(3)    // this call fails
a1.h(5)

对于 a1.g(3) 我得到这个错误:
<console>:10: error: method g in trait A cannot be accessed in A{def h(i: Int): Unit}
   Access to protected method g not permitted because
   enclosing object $iw is not a subclass of 
   trait A where target is defined
                      a1.g(3)    // this call fails

但是当我定义一个扩展 A 并覆盖方法 f 和 g 的特征 A2 时,创建它的一个实例并调用这些方法,一切正常
trait A2 extends A {
    override def f( i: Int ) = super.f(i)
    override def g( i: Int ) = super.g(i)
    def h( i: Int ) = super.g(i)
}
val a2= new A2 {}

a2.f(2)
a2.g(4)
a2.h(6)

为什么有区别
val a1= new A {
    override def g( i: Int ) = super.g(i)
}


trait A2 extends A {
    override def g( i: Int ) = super.g(i)
}
val a2= new A2 {}

?

谢谢!

最佳答案

我会继续让我的评论成为答案。 It's a bug .它确实应该按照您期望的方式工作,但事实并非如此。

关于scala 覆盖 protected 成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21680043/

相关文章:

scala - 从Groovy调用Scala:如何处理不同的集合类型?

Scala 向后兼容性

scala - 无法在 Windows 上使用 0.13.1 为对象堆保留足够的空间?

scala - 方法在语义上等同于 Scala 3 中的函数吗?

scala - SBT:子项目中的 plugins.sbt 被忽略?

java - Java/Scala 中的液体标记

java - 内容类型为 : text throws an "Unhandled content type "null""exception in Jsoup 的 IIS 响应

具有多个隐式参数的函数文字

java - 用于 java 或 scala 中整数分解的库

scala - 在 Scala 中 - 将案例类列表转换为元组列表