简体   繁体   中英

Getting around type erasure: problem with trait type!

I want to get around type erasure in match case using the code from here :

 class Def[C](implicit desired: Manifest[C]) {

        def unapply[X](c: X)(implicit m: Manifest[X]): Option[C] = {
          def sameArgs = desired.typeArguments.zip(m.typeArguments).forall {
            case (desired, actual) => desired >:> actual
          }
          if (desired >:> m && sameArgs) Some(c.asInstanceOf[C])
          else None
        }
 }

This code i can use to match types which are normally erased. example:

val IntList = new Def[List[Int]]
List(1,2,3,4) match { case IntList(l) => l(1)   ; case _ => -1 }

instead of:

List(1,2,3,4) match { case l : List[Int] => l(1) ; case _ => -1}//Int is erased!

but i got a problem with the Type system:

trait MyTrait[T]{
  type MyInt=Int
  val BoxOfInt=new Def[Some[MyInt]] // no problem
  type MyType = T
  val BoxOfMyType=new Def[Some[MyType]]// could not find....
}

That Problem results in:

could not find implicit value for parameter desired: Manifest[Some[MyTrait.this.MyType]]
[INFO]   val BoxOfMyType=new Def[Some[MyType]]
[INFO]                   ^

How can i get the required type into the Manifest or how could i change the code so that it works without errors or warnings?!

Thanks for any Help

You need a Manifest for the type T . If you were declaring a class instead of a trait, the following would work:

class MyTrait[T : Manifest]{
  type MyType = T
  val BoxOfMyType=new Def[Some[MyType]]
}

If you really do need a trait and not a class, one alternative would be to require that all subclasses provide the Manifest somehow, eg:

trait MyTrait[T]{
  type MyType = T
  implicit val MyTypeManifest: Manifest[T]
  val BoxOfMyType=new Def[Some[MyType]]
}

class X extends MyTrait[Int] {
  val MyTypeManifest = manifest[Int]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM