Search code examples
scalaenumspath-dependent-type

How to deal with enumerations and path-dependent types in Scala


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

Solution

  • You can use a path dependent type there but it's an experimental feature right now. Use -Xexperimental for scala or scalac.

    $ 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)