如何在 Scala 中处理枚举和路径依赖类型
我遇到一个问题,其解决方案应该与此问题的解决方案等效:假设我想编写一个方法,给定一个枚举,返回其所有值的列表。我想写:
def makeList[E <: Enumeration](enum: E): List[enum.Value] = enum.values.toList
但是编译失败并出现非法依赖方法类型
错误。改为这样写可以吗?
def makeList[E <: Enumeration](enum: E): List[E#Value] = enum.values.toList
I'm having a problem whose solution should be equivalent to the solution to this: Suppose I want to write a method which, given an Enumeration, returns a list of all its values. I want to write:
def makeList[E <: Enumeration](enum: E): List[enum.Value] = enum.values.toList
but compilation fails with an illegal dependent method type
error. Is it OK to write this instead?
def makeList[E <: Enumeration](enum: E): List[E#Value] = enum.values.toList
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以在那里使用路径相关类型,但它现在是一个实验性功能。对 scala 或 scalac 使用 -Xexperimental。
You can use a path dependent type there but it's an experimental feature right now. Use -Xexperimental for scala or scalac.
对我来说似乎没问题:
更新回复评论:
我猜有人可以重写
Value
嵌套类而不是Val
(我只是查看了来源,它没有被密封),但我想不出理由。请注意,通常,对于所有枚举,Value
都是相同的类型:It seems to be OK to me:
UPDATE in reply to the comment:
I guess someone could override the
Value
nested class instead ofVal
(I just looked at the source and it isn't sealed), but I can't think of a reason to. Note that normally, for all enumerations,Value
is the same type: