有没有办法引用由同名抽象类型成员遮蔽的泛型类型参数?
假设我们有一个 trait 和扩展类:
trait Foo {
type T
var get: T = _
}
class Bar[X] extends Foo {
override type T = X //We can set the type member by referencing the generic parameter X
}
class Baz[T] extends Foo {
override type T = ??? //How can we reference the generic parameter T here?
}
显然,将泛型参数命名为与类型成员不同的名称通常没什么大不了的,但这并不总是最好的选择(例如,当使用外部库时)。有没有办法引用阴影泛型参数? Scala 规范中的何处描述了类型成员和泛型参数之间的这种交互?
最佳答案
即使没有覆盖特征的抽象成员,类型 T
将始终引用继承的类型成员,而不是泛型参数。这是一个已知问题,归档为 SI-8421 .从提议的修复中,解释了为什么这是一个错误:
When binding a name to a symbol, we search up through the context chain. At each step, we first look in the current scope. If that fails, we look for members of the prefix of the closest enclosing context associated with a
Template
orPackageDef
.However, this means we will look for an inherited type member before finding an eponymous class type parameter, which is in the scope of an enclosing context two levels out.
因此,也许在该问题解决后(标记为 2.12.0-M2),即使抽象类型成员被覆盖,也可以引用阴影类型。
关于scala - 引用由抽象类型成员遮蔽的泛型类型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30112660/