开发者

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] =&g开发者_JS百科t; 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, e.g.:

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]
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜