绕过类型擦除:特征类型的问题!
我想使用 此处:
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] ^
我如何将所需的类型添加到清单中,或者如何更改代码以使其在没有错误或警告的情况下工作?!
感谢您的帮助
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要类型
T
的Manifest
。如果您声明一个类而不是一个特征,则以下内容将起作用:如果您确实需要一个特征而不是一个类,一种替代方法是要求所有子类以某种方式提供
Manifest
,例如:You need a
Manifest
for the typeT
. If you were declaring a class instead of a trait, the following would work: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.: