如何为类编写Scala匹配器?

yur*_*ura 3 scala pattern-matching

假设我有以下代码

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)
   }
Run Code Online (Sandbox Code Playgroud)

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

Mil*_*bin 5

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

// 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)
Run Code Online (Sandbox Code Playgroud)

使用此实现,如果您要求不支持的类型,则不会在运行时得到匹配错误,而是会得到静态编译时错误。

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