scala - Pattern matching dependent types - how to avoid asInstanceOf? -


i'm drawing blank on how accomplish following without cheating , using asinstanceof.

say have arbitrary sealed type of objects, each own type members.

  sealed trait part { type }   case object p1 extends part { override type = string }   case object p2 extends part { override type = int } 

now bundle p , p.a value together...

  trait partanda {     val p: part     val a: p.a   }    object partanda {     type aux[p <: part] = partanda {val p: p}      def apply(_p: part)(_a: _p.a): aux[_p.type] =       new partanda {         override val p: _p.type = _p         override val          = _a       }   } 

how can safely accomplish following exhaustion checking , without manual casts?

  def fold[a](pa: partanda)(p1: partanda.aux[p1.type] => a,                             p2: partanda.aux[p2.type] => a): =     pa.p match {       case p1 => p1(pa.asinstanceof[partanda.aux[p1.type]])       case p2 => p2(pa.asinstanceof[partanda.aux[p2.type]])     } 

i think problem connected jvm type erasure. without problem simplified to:

sealed trait part { type } case class p1() extends part { override type = string } case class p2() extends part { override type = int }  trait partanda[p <: part] {   val p: p   val a: p.a }  object partanda {   type aux[p <: part] = partanda[p]    def apply(_p: part)(_a: _p.a): partanda[_p.type] =     new partanda[_p.type] {       override val p: _p.type = _p       override val          = _a     } }  def fold[a, t: classtag](pa: partanda[t])(p1: partanda[p1] => a,                           p2: partanda[p2] => a): =   pa match {     case s: partanda[p1]  => p1(pa) // here p1 lost, err      case i: partanda[p2] => p2(pa) // here p2 lost, err   } 

according knowledge there no shorter (than yours or typetags/classtags) workaround of jvm type erasure.


Comments

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -