我有一个案例类,有多个参数,其中一些是选项。这里是一个简化的例子:案例分类有选项参数和案例匹配
case class Foobar(a: String, b: Option[String], c: Option[CustomClass])
我希望能够匹配foobar案件,其中b和/或c不是无。例如,一种情况可能是:
testResult match {
case Foobar("str1", Some(_), None) => "good"
case Foobar("str2", None, Some(_)) => "ok"
case _ => "bad"
}
此外,我想通过变量引用例模式,这就是我卡住了。我想要做的事情如下:
val goodPat = Foobar("str1", Some(_), None) // compile fail
val okPat = Foobar("str2", None, Some(_)) // compile fail
testResult match {
case `goodPat` => "good"
case `okPat` => "ok"
case _ => "bad"
}
是这样的可能吗?是否有另一种方式来指定“不是”?是否有另一种方法来解决这个问题?
编辑:我添加更多的细节和上下文的问题。我有一个大的2元组列表,代表特定函数的单元测试。 2元组表示输入和期望输出。例如。
// imagine this list is much bigger and Foobar contains more Option parameters
val tests = List(
("test1", Foobar("idkfa", None, None)),
// I know these fail to compile but I need to do something like this
("test2", Foobar("idclip", Some("baz"), Some(_)),
("test3", Foobar("iddqd", Some(_), None)
)
tests.foreach(test => {
val (input, expected) = test
myFunction(input) match {
case `expected` => println("ok")
case _ => println("bad")
}
})
你为什么会想要在案例类中匹配变量名?我不认为这是必要的。你的第一种方法有什么问题? –
我没有匹配变量名称。我试图将模式定义移到匹配块之外,因为实际的代码更加复杂,我需要以编程方式分配模式。 – beetea
'val a = Foo(x)'是intantiaing类的语法。这里不能使用'_'这样的通配符模式匹配器。 –