简体   繁体   中英

Conversion and type erasure

Is there a better way to write this block of code? In particular is it possible to factor the conversion in a external function?

nodes collect { case x: InstrumentSource[_] if (x.m <:< implicitly[ClassManifest[BarClose]]) => x.asInstanceOf[InstrumentSource[BarClose]] };

m in InstrumentSource is a class manifest:

case class InstrumentSource[A](implicit val m: ClassManifest[A])

and nodes is a collection of various InstrumentSource.

My idea is:

trait HasClassManifest[A] {
  def m: ClassManifest[A]    
}

object <-< {
  def apply[A : ClassManifest](a: HasClassManifest[_]): Boolean = {
    a.m <:< classManifest[A]
  }
}

case class InstSource[A](implicit m: ClassManifest[A]) extends HasClassManifest[A]

Seq(InstSource[Long],InstSource[Double]) collect {
  case x if <-<[Long](x)   => println("long")
  case x if <-<[Double](x) => println("double")
}

(Renamed InstrumentSource to InstSource for not scrolling here)
So the price is defining HasClassManifest and <-< once and every class you want to patternmatch on has to extend HasClassManifest . That´s all.
But I don´t know how to factor out the instanceOf conversion on the right hand side at the moment.

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