您可以从案例类的伴随对象中提取unapply
方法并使用它:
scala> :paste
// Entering paste mode (ctrl-D to finish)
abstract class A(field: String)
case class B(f: String) extends A(f)
case class C(f: String) extends A(f)
case class E(f: String, f1: Int) extends A(f)
case class F(f: String, f1: Int) extends A(f)
class Unapplyer[T: Manifest, R](f: T => Option[R]) {
def unapply(a: Any): Option[R] = {
if (manifest[T].erasure.isInstance(a)) f(a.asInstanceOf[T]) else None
}
}
def printer[T: Manifest, R](a: A, b: T => Option[R]) {
val P = new Unapplyer(b)
a match {
case P((f, f1)) => println(f + " - " + f1)
case P(f) => println(f)
case _ => println("oops")
}
}
// Exiting paste mode, now interpreting.
defined class A
defined class B
defined class C
defined class E
defined class F
defined class Unapplyer
printer: [T, R](a: A, b: (T) => Option[R])(implicit evidence$2: Manifest[T])Unit
scala> printer(B("test"), B.unapply _ )
test
scala> printer(B("test"), C.unapply _ )
oops
scala> printer(E("test", 1), E.unapply _ )
test - 1
scala> printer(E("test", 1), F.unapply _ )
oops
scala> printer(E("test", 1), B.unapply _ )
oops
UPD:添加了可变数量和类型的参数的用法。