yura
yura

Reputation: 14645

How to write scala matcher for class?

Assume I have follwing code

def get[T](name:String)(implicit mf:ClassManifest[T]):T = mf.erasure match {
     case classOf[Boolean] => obj.getBoolean(name)
     case classOf[Int] => obj.getInt(name)
   }

Now code dosn't work because classOf[Int] is invalid match value.

Upvotes: 3

Views: 427

Answers (2)

Miles Sabin
Miles Sabin

Reputation: 23046

You should almost certainly investigate alternatives to using manifests and matching on class objects. In this case type classes will provide a much cleaner solution,

// Assuming that Store is the type of obj ...

trait Get[T] { def get(s : Store, name : String) : T }
implicit val getBoolean = new Get[Boolean] {
  def get(s : Store, name : String) : Boolean = s.getBoolean(name)
}
implicit val getInt = new Get[Int] {
  def get(s : Store, name : String) : Int = s.getInt(name)
}

def get[T](name : String)(implicit inst : Get[T]) : T = inst.get(obj, name)

With this implementation, rather than getting a match error at runtime if you ask for an unsupported type, you will instead get a static compile time error.

Also note that being a compile time resolution mechanism, applied before erasure, this technique is a lot more precise than matching at runtime post-erasure. For instance, using this technique we can distinguish between the List[Int] and List[String] case, whereas they would be equated by a runtime test.

Upvotes: 5

Dylan
Dylan

Reputation: 13922

This works for me:

val mf = //some manifest
mf.erasure match {
  case c if c == classOf[String] => "string!"
  case c if c == classOf[Int] => "int!"
  case c if c == classOf[Boolean] => "bool!"
  //...
}

Upvotes: 3

Related Questions