gpt4 book ai didi

scala 覆盖 protected 成员函数

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

我想实例化一个特征并覆盖 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/

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