Scala: Pattern match multiple Option arguments
pattern-matching, scala
Solution
I'm not sure I understood what you're looking for, but :
private def msgPrefix(implicit myClass: MyClass, anotherClass: AnotherClass) = {
(Option(myClass), Option(anotherClass)) match {
case (Some(validMyClass), Some(validAnotherClass)) => validMyClass.process + validAnotherClass.process
case _ => ""
}
}
This will return the empty String if at least one of the two arguments is null, ie :
scala> msgPrefix(MyClass("foo"),null)
res2: String = ""
scala> msgPrefix(MyClass("foo"),AnotherClass("bar"))
res3: String = foobar
But you probably should just change the type of the arguments to `Option[MyClass]` and `Option[AnotherClass]` (if you can).
Problem
I would like to achieve something like the following: ``` private def msgPrefix(implicit myClass: MyClass, anotherClass: AnotherClass) = { Option(myClass, anotherClass) match { case Some(validMyClass, validAnotherClass) => validMyClass.process + validAnotherClass.process case _ => "" } } ``` What is the right way to do this?