如何在Scala中访问泛型类型的类型别名?
也就是说,我想为枚举编写自己的 valueOf,因为 Scala 设计者现在已删除此方法(奇怪的调用 - https://issues.scala-lang.org/browse/SI-4571)。
def valueOf[E <: Enumeration](s : String) =
E#Value.values.filter(it => it.toString==s).single()
不要太关注 single,它只是类似 Linq 的包装器(请参阅:Scala 中的 IEnumerable LINQ 等效项图表?)。
问题出在 E#Value 上。
问题
如何正确访问这个别名,即如何访问泛型类型的类型别名? 请以此枚举为例!
有 withName 方法,即使它被认为是替换,它也被设计破坏了,值不是名称,所以我不会使用它,以避免进一步混淆代码正在做什么。
Namely I would like to write my own valueOf for enums, since this method is removed now by Scala designers (odd call -- https://issues.scala-lang.org/browse/SI-4571).
def valueOf[E <: Enumeration](s : String) =
E#Value.values.filter(it => it.toString==s).single()
Don't pay much attention to single, it is just Linq-like wrapper (see: Chart of IEnumerable LINQ equivalents in Scala?).
The problem is with E#Value.
Question
How do I access this alias correctly, i.e how do I access type alias of generic type? Please treat this Enum as example!
There is withName method, even if it is considered replacement it is broken by design, value is not a name, so I won't use it to avoid further confusion what the code is doing.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该示例的问题在于枚举被声明为对象。无法根据类名查找对象实例,因此稍作更改即可修复此问题。另外,对于泛型,find 方法已经偏离了 Enumeration 中声明的抽象 Value 类型,因此我们需要添加一个 instanceOf 来修复类型。至于
通用别名,E#Value 是正确的。这提供了良好的打字效果。
The problem with the example is that Enumerations are declared as objects. The object instance can't be looked up based on the class name so a minor change fixes this. Also, do to generics the find method has already digressed to the abstract Value type declared in Enumeration so we need to add an instanceOf to fix the typing. As for the
generic alias, E#Value is correct. This provides good typing.