简体   繁体   English

解决类型擦除:特征类型问题!

[英]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 . 您需要Manifest TManifest 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: 如果您确实确实需要特征而不是类,则一种替代方法是要求所有子类都以某种方式提供Manifest ,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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