4

我如何在 scala 中编写 isCaseObject 函数,这样才能工作:

def isCaseObject(x:Any) = /* Some Code */

case object aCaseObject
println(isCaseObject(aCaseObject)) //true
println(isCaseObject("not a case object")) //false
4

2 回答 2

10

使用反射(Scala 2.10M4),可以按如下方式完成:

import scala.reflect.runtime.universe.Flag
import scala.reflect.runtime.{ currentMirror => cm }

object Check {

  def isCaseObject(x:Any): Boolean = {
    cm.reflect(x).symbol.hasFlag(Flag.CASE)
  }

}
于 2012-07-10T23:55:09.673 回答
2

All case classes extend Product, so you can use the type system:

 def isCC[A](a: A)(implicit ev: A <:< Product) = a

If you try and call it with a not Product:

scala> isCC("test")
<console>:17: error: Cannot prove that java.lang.String <:< Product.
              isCC("test")

But you can call it with a case class:

scala> case class CA(a: Int)
defined class CA

scala> isCC(CA(1))
res19: CA = CA(1)
于 2012-07-11T01:22:31.283 回答