简体   繁体   中英

What's the easiest way to circumvent [SI-6976] in scala 2.10 for primitive collection pattern matching?

I have a simple function:

  implicit class ArrayView[A](self: Array[A]) {

    def filterByType[B <: A: ClassTag]: Array[B] = {
      val ctg = implicitly[ClassTag[B]]

      val runtimeClazz = ctg.runtimeClass

      self.flatMap{
        v =>
          if (v.getClass.isAssignableFrom(runtimeClazz)) Some(v.asInstanceOf[B])
          else None
      }.toArray
    }
  }

and a simple test case:

assert(Array(1, 2.2, "a").filterByType[Int].toSeq == Seq(1))
assert(Array(1, 2.2, "a").filterByType[java.lang.Integer].toSeq == Seq(1: java.lang.Integer))
assert(Array(1, 2.2, "a").filterByType[Double].toSeq == Seq(2.2))
assert(Array(1, 2.2, "a").filterByType[java.lang.Double].toSeq == Seq(2.2: java.lang.Double))
assert(Array(1, 2.2, "a").filterByType[String].toSeq == Seq("a"))

it only works in Scala >2.11.3 (because of https://issues.scala-lang.org/browse/SI-6967 , this has been brought about for some time), but many libraries (eg spark-hive_thriftserver) still have problems being ported to 2.11, while 2.10 has been largely stable for most other cases, is there a quick patch for this bug?

OK this is really funky, but whatever:

  implicit class ArrayView[A](self: Array[A]) {

    def filterByType[B <: A: ClassTag]: Array[B] = {
      self.flatMap{
        v =>
          try {
            Array[B](v.asInstanceOf[B])
          }
          catch {
            case e: Throwable =>
              Array[B]()
          }
      }.toArray
    }
  }

pass all the tests

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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