I have different kinds of enumerations in this flavour
class Gender extends Enumeration {
type Gender = Value
val Male,Female = Value
}
and I would like to have a generic function that given an element of an enumeration, it puts a 1 in an array of length .maxId (if you are familiar with R, I’m trying to implement factor). But I’m not able to get the types right, my function would be something like this (wrong) code:
def toFactor[T](elem:T.Value):List[Double] = {
var array = Array.fill(T.maxId)(0.0)
array(elem.id) == 1.0
array.toList
}
How would you write this code so is generic for whatever enumeration we use?
This code should do it:
You need to use
E#Valueinstead ofE.Valuebecause it generally tells: anyValueof the providedEnumerationE.E <: EnumerationrestrictsEto be subclass ofEnumeration. You also need enum instance in order to getmaxId.Update
You can also simplify
toFactormethod a little bit and avoid using anyArrays orids: