scala - 引用由抽象类型成员遮蔽的泛型类型参数

标签 scala generics type-members

有没有办法引用由同名抽象类型成员遮蔽的泛型类型参数?

假设我们有一个 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 or PackageDef.

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/

相关文章:

scala - 如何使用 Scala 将数据作为元组传递到 Spark 中的 rdd

scala - 花括号和括号之间在Scala中的形式差异是什么?何时使用?

scala - 我怎样才能压平这个 Future[T] 结构?

ios - 在 Swift 中使用泛型数组作为参数的函数

swift - 如何使用泛型推断类型?

scala - 类型成员为 : what is Scala's object vs module system ? 的对象(试图理解 2014 年 Odersky 关于路径相关类型的论文)

scala - 引用类型参数的抽象类型成员

Scala 子类型不被接受

c# - 我可以创建泛型字典吗?

scala - 具有类型成员的隐式包装特征无法编译