也许你可以忍受case class Foo(a: Int, b: Int)(val c: Boolean = true)
。
更新:如果你几乎可以忍受,因为你不想在模式中使用额外的参数,那么你可以做一些简短的工作。
package fooplusplus
case class Foo(a: Int, b: Int) {
def c: Boolean = true
}
object Foo {
def apply(a: Int, b: Int, c: Boolean): Foo =
new {
private[this] val x = c // http://stackoverflow.com/a/12239654
} with Foo(a, b) {
override def c = x
}
}
object Test extends App {
def bar(x: Foo) = x match {
case Foo(1, 2) if !x.c => 3
case Foo(1, 2) => 2 // existing code
case _ => 1
}
Console println bar(Foo(1, 2))
Console println bar(Foo(1, 2, c = false))
Console println bar(Foo(0, 2))
}
如果您确实希望与新参数进行模式匹配,这是一种方法:
case class EnhancedFoo(a: Int, b: Int, c: Boolean)
class Foo(a: Int, b: Int, c: Boolean) extends EnhancedFoo(a, b, c)
object Foo {
def apply(a: Int, b: Int, c: Boolean = true): Foo = new Foo(a, b, c)
def unapply(x: Foo): Option[(Int, Int)] = Some(x.a, x.b)
}
object Test extends App {
def bar(x: EnhancedFoo) = x match {
case EnhancedFoo(1, 2, true) => 3
case Foo(1, 2) => 2 // existing code
case _ => 1
}
Console println bar(Foo(1, 2))
Console println bar(Foo(1, 2, c = false))
Console println bar(Foo(0, 2))
}
既然我们还没有做任何真正古怪的事情,那么以下内容如何:
scala> case class Foo(a: Int, b: Int, c: Boolean*)
defined class Foo
scala> import PartialFunction._
import PartialFunction._
scala> val foo = Foo(1,2)
f: Foo = Foo(1,2,WrappedArray())
scala> val goo = Foo(1,2,true)
g: Foo = Foo(1,2,WrappedArray(true))
scala> cond(foo) { case Foo(1,2) => true }
res0: Boolean = true
scala> cond(goo) { case Foo(1,2,false) => true }
res1: Boolean = false
布尔值变为三态,默认为旧式空。
scala> cond(foo) { case Foo(1,2, _ @ _*) => true }
res2: Boolean = true
scala> cond(foo) { case Foo(1,2, x) => true }
res3: Boolean = false
scala> cond(goo) { case Foo(1,2, x @ _*) if x exists identity => true }
res4: Boolean = true