声明一个接受未知案例类作为参数的方法,以便在Scala中的模式匹配中使用它

Tia*_*ida 1 methods arguments scala pattern-matching case-class

想象一个抽象的A类,它有一组案例类.我们不知道有多少集合类,甚至不知道这些案例类的名称.

abstract class A(field: String)
//Example of a case class that extends A
case class B(f: String) extends A(f)
Run Code Online (Sandbox Code Playgroud)

现在我有这个:

a match {
    case B(f) => println("f")
}
Run Code Online (Sandbox Code Playgroud)

我想通过参数将case类类型传递给方法.我想要这个的原因是因为我将在文件中配置一组规则.我想加载这些规则并使用模式匹配与这些规则提供的一些信息.我想做这样的事情:

def printer (a: A, B: A) = {
   a match{
       case B(f) => println("f")
   }
}
Run Code Online (Sandbox Code Playgroud)

这可能吗?

如果不是那么容易,我可以在模式匹配中使用抽象类吗?如果我可以简单地使用抽象类,那将是完美的,因为它具有所有案例类的主要结构.

编辑:

忘了提一下,case类可以有不同的参数,所以使用基于类A的东西会很好(因为我可以只使用字段匹配模式)

Hei*_*ger 5

不像你试过的那样.但是如果你使用Manifest作为上下文绑定,你可以使它工作:

scala> trait Foo
defined trait Foo

scala> case class Bar(baz: String) extends Foo
defined class Bar

scala> def boo[A <: Foo : Manifest](foo: Foo) =
     |   if (foo.getClass isAssignableFrom manifest[A].erasure) "foo" else "boo"
boo: [A <: Foo](foo: Foo)(implicit evidence$1: Manifest[A])java.lang.String

scala> boo[Foo](Bar(""))
res0: java.lang.String = boo

scala> boo[Bar](Bar(""))
res1: java.lang.String = foo
Run Code Online (Sandbox Code Playgroud)