scala - Restricting generic type to an enumeration type -


say want define generic type , have guarantee instantiated when generic parameter 1 of known list of types. 1 way that, using typeclasses, is

sealed trait allowed[a] object allowed {   implicit object string extends allowed[string]   implicit object int extends allowed[int] } case class player[a: allowed](id: a, name: string, score: double) 

in case, know player can have id string or int, nothing else. can leverage information in functions such following

def retrieveplayerbyid[a: allowed](p: player[a]) =   implicitly[allowed[a]] match {     case allowed.string =>       val id = p.id.asinstanceof[string]       ...     case allowed.int =>       val id = p.id.asinstanceof[int]       ...   } 

now, problem following. same, allowing generic parameter either string, or enumeration type.

i not care if enumerations encoded this:

object weekday extends enumeration {   type weekday = value   val mon, tue, wed, thu, fri, sat, sun = value } 

or this

trait weekday case object mon extends weekday case object tue extends weekday case object wed extends weekday case object thu extends weekday case object fri extends weekday case object sat extends weekday case object sun extends weekday 

although former little more convenient other reasons.

any ideas how that?

edit: first attempt goes this

sealed trait allowed[a] object allowed {   implicit object string extends allowed[string]   implicit def enum[a <: enumeration] = new allowed[a#value] {} } 

this works in restricting type, problem pattern matching on it. can do

def foo[a: allowed] = implicitly[allowed[a]] match {   case allowed.string =>     // ok in branch   case _ =>     // here don't know how persuade compiler     // enumeration type } 

in order convince compiler have enumeration type, have tried matching with

case n: allowed[(a forsome { type <: enumeration })#value] => 

or similarly

case n: allowed[a#value forsome { type <: enumeration }] => 

but both rejected compiler saying value not type member of a (even though constrain a extend enumeration)


Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

java.lang.NoClassDefFoundError When Creating New Android Project -

Decoding a Python 2 `tempfile` with python-future -