如何为类编写Scala匹配器? [英] How to write scala matcher for class?

查看:51
本文介绍了如何为类编写Scala匹配器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下代码

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)
   }

现在代码不起作用,因为 classOf[Int] 是无效的匹配值.

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

推荐答案

您几乎肯定应该研究在类对象上使用清单和匹配的替代方法.在这种情况下,类型类将提供更简洁的解决方案,

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.

另请注意,作为一种编译时解析机制,在擦除之前应用,此技术比在运行时后擦除时匹配要精确得多.例如,使用这种技术,我们可以区分 List[Int]List[String] 两种情况,而它们将被运行时测试等同起来.

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.

这篇关于如何为类编写Scala匹配器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆