【发布时间】:2016-08-17 04:17:40
【问题描述】:
我有一个案例类,它有多个参数,其中一些是选项。这是一个简化的例子:
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")
}
})
【问题讨论】:
-
为什么要匹配case类中的变量名?我认为没有必要。您的第一种方法有什么问题?
-
我没有匹配变量名。我正在尝试将模式定义移到匹配块之外,因为实际代码要复杂得多,我需要以编程方式分配模式。
-
val a = Foo(x)是用于创建类的语法。你不能在这里使用像_这样的通配符模式匹配器。 -
好的,所以你有一长串测试名称和预期结果的元组。你是说对于某些测试你不关心 b 参数的字符串值是什么?而对于许多其他人来说,您关心 b 参数的字符串值到底是什么?
-
@Samar 是的,这是正确的:有时确切的 b 参数并不重要,我只需要知道它不是 None
标签: scala