alex_C
alex_C

Reputation: 105

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.

Upvotes: 2

Views: 122

Answers (1)

Peter Schmitz
Peter Schmitz

Reputation: 5844

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.

Upvotes: 1

Related Questions