0

Is there any way to refer to a type parameter?

For example i have wantd to make a class that gets Sub class of Enumeration and than use him: example of what i wanted :

class MyEnum1 extends Enumeration{
    type MyEnum=Value
    a1=Value("A1")
    b1=Value("B1")
}

class MyEnum2 extends Enumeration{
    type MyEnum=Value
    a2=Value("A2")
    b2=Value("B2")
}


class UseType[T:<Enumeration]{
    val values=T.values
}

Do you know how can i do it?

David H
  • 1,346
  • 3
  • 16
  • 29

1 Answers1

2

I think you need to work at the object level, not the type level, and pass an instance (which can be a singleton object) into your class:

object MyEnum1 extends Enumeration {
  type MyEnum1 = Value
  val a1 = Value("A1")
  val b1 = Value("B1")
}

object MyEnum2 extends Enumeration {
  type MyEnum2 = Value
  val a2 = Value("A2")
  val b2 = Value("B2")
}

class UseType[T <: Enumeration](val t: T) {
  println(t.values)
}

new UseType(MyEnum1)              //> MyEnum1.ValueSet(A1, B1)
new UseType(MyEnum2)              //> MyEnum2.ValueSet(A2, B2)

I'm not quite sure why you would want to do this, though - can you explain what you are trying to achieve? You might need to give MyEnum1 and MyEnum2 an additional shared trait in order for them to work interchangeably in your code?

See also this question and this one, and also this one - depending on your use case, you might prefer to use sealed case classes.

Community
  • 1
  • 1
DNA
  • 42,007
  • 12
  • 107
  • 146
  • why did you wrote [T <: Enumeration](**val** t: T) when i was tryng to write it without val it didnt compile. Any idea? – David H Apr 02 '14 at 10:46
  • I'm not sure why I added the `val` ! - it's only needed if you want to refer to `t` as a property of the `UseType`, e.g. `UseType(MyEnum1).t` – DNA Apr 02 '14 at 12:03