我遇到了一个问题,其解决方案应该等同于解决方案:假设我想编写一个方法,给定一个Enumeration,返回其所有值的列表。我想写:
def makeList[E <: Enumeration](enum: E): List[enum.Value] = enum.values.toList
但编译失败,出现illegal dependent method type
错误。可以写这个吗?
def makeList[E <: Enumeration](enum: E): List[E#Value] = enum.values.toList
答案 0 :(得分:3)
您可以在那里使用路径依赖类型,但它现在是一个实验性功能。对scala或scalac使用-Xexperimental。
$ scala -Xexperimental
Welcome to Scala version 2.8.1.final (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_21).
Type in expressions to have them evaluated.
Type :help for more information.
scala> def makeList[E <: Enumeration](enum: E): List[enum.Value] = enum.values.toList
makeList: [E <: Enumeration](enum: E)List[enum.Value]
scala> object Bool extends Enumeration {
| type Bool = Value
| val True, False = Value
| }
defined module Bool
scala> makeList(Bool)
res0: List[Bool.Value] = List(True, False)
答案 1 :(得分:1)
对我来说似乎没问题:
object WeekDay extends Enumeration {
type WeekDay = Value
val Mon, Tue, Wed, Thu, Fri, Sat, Sun = Value
}
> makeList(WeekDay)
res2: List[WeekDay#Value] = List(Mon, Tue, Wed, Thu, Fri, Sat, Sun)
> makeList(WeekDay.Mon)
error: inferred type arguments [WeekDay.Value] do not conform to method makeList's type parameter bounds [E <: Enumeration]
makeList(WeekDay.Mon)
^
更新回复评论:
我猜某人可以覆盖Value
嵌套类而不是Val
(我只看了源而且没有密封),但我不能想到一个理由。请注意,通常,对于所有枚举,Value
都是相同的类型:
object Bool extends Enumeration {
type Bool = Value
val True, False = Value
}
> Bool.True.getClass
res8: java.lang.Class[_] = class scala.Enumeration$Val
> Bool.True.getClass == WeekDay.Mon.getClass
res7: Boolean = true