[英]Getting around type erasure: problem with trait type!
我想用代碼來解決類型擦除在比賽的情況下在這里 :
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
}
}
我可以使用此代碼來匹配通常擦除的類型。 例:
val IntList = new Def[List[Int]]
List(1,2,3,4) match { case IntList(l) => l(1) ; case _ => -1 }
代替:
List(1,2,3,4) match { case l : List[Int] => l(1) ; case _ => -1}//Int is erased!
但是我遇到了類型系統的問題:
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....
}
該問題導致:
could not find implicit value for parameter desired: Manifest[Some[MyTrait.this.MyType]]
[INFO] val BoxOfMyType=new Def[Some[MyType]]
[INFO] ^
我如何才能將所需的類型放入清單中,或者如何更改代碼以使其在沒有錯誤或警告的情況下起作用?
謝謝你的幫助
您需要Manifest
T
的Manifest
。 如果您聲明的是類而不是特征,則可以使用以下方法:
class MyTrait[T : Manifest]{
type MyType = T
val BoxOfMyType=new Def[Some[MyType]]
}
如果您確實確實需要特征而不是類,則一種替代方法是要求所有子類都以某種方式提供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.