Reputation: 1202
I have a case class like this:
case class Foo(a : Option[String], b : Option[String])
and I want to pattern match on it to see if the values are present in the fields or not. What is the best way to do this?
I did the following but it doesn't work because it is thinking I am trying to create an instance of Foo:
val ff = Foo(Some("a"), None)
//psuedo code
ff match {
case Foo(a, b) => do something // all values present
case Foo(None, None) => error
Upvotes: 0
Views: 731
Reputation: 20285
case Foo(a,b)
will match any Foo(Option, Option)
since you are not matching on an instance of Option
. e.g. Some
or None
.
See Luis's comment above too.
scala> ff match{
| case Foo(None, None) => "nn"
| case Foo(None, Some(a)) => "ns"
| case Foo(Some(a), None) => "sn"
| case Foo(Some(a), Some(b)) => "ss"
| }
res4: String = sn
Upvotes: 1
Reputation: 2527
You can do following:
case class Foo(a: Option[String], b: Option[String])
val ff = Foo(Some("a"), None)
//psuedo code
ff match {
case Foo(Some(a), Some(b)) => // when both a and b present
case Foo(Some(a), None) => // when only a present
case Foo(None, Some(b)) => // when only b present
case Foo(None, None) => // when both a and b are not present
}
Upvotes: 1