How to write scala matcher for class?

时光怂恿深爱的人放手 提交于 2020-05-13 08:00:26

问题


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.


回答1:


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.




回答2:


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!"
  //...
}


来源:https://stackoverflow.com/questions/9488405/how-to-write-scala-matcher-for-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!