简体   繁体   English

Scala isInstanceOf [T]函数无法使用有限的ClassTag / TypeTag

[英]Scala isInstanceOf[T] function fail to use bounded ClassTag/TypeTag

The follow code: 以下代码:

abstract class Foo[T: ClassTag] {
    def v(a: Any): Any = a match {
        case _ if a.isInstanceOf[T] => Some(a)
        case _ => None
    }
}

yield the following in compilation: 在编译中产生以下内容:

Warning: abstract type T is unchecked since it is eliminated by erasure
    case _ if a.isInstanceOf[T] =>

Strangely, case match will work as intended. 奇怪的是,大小写匹配将按预期工作。 Is there a way to make isInstanceOf[T] be aware of the ClassTag context bound as well? 有没有办法让isInstanceOf [T]也知道ClassTag上下文绑定?

I wouldn't say this is working as expected: 我不会说这按预期工作:

scala> (new Foo[String] {}).v(List(1))
res10: Any = Some(List(1)) // Not a String!

Don't use isInstanceOf , as it doesn't use ClassTag s at all. 不要使用isInstanceOf ,因为它根本不使用ClassTag You can use the ClassTag extractor, instead: 您可以改用ClassTag提取器:

abstract class Foo[T: ClassTag] {
    def v(a: Any) = a match {
        case _: T => Some(a)
        case _ => None
    }
}

scala> (new Foo[String] {}).v(1)
res3: Option[Any] = None

scala> (new Foo[String] {}).v("abc")
res4: Option[Any] = Some(abc)

This is all syntactic sugar for: 这是所有语法糖:

abstract class Foo[T](implicit ct: ClassTag[T]) {
    def v(a: Any) = a match {
        case ct(a) => Some(a)
        case _ => None
    }
}

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

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