rabejens
rabejens

Reputation: 8122

What is the proper way of doing partial matches in Scala?

I have a Properties object, and want to do something if the configuration contains a specific key. If this key does not exist, I simply want to ignore it. I tried it the following way:

myProps getProperty "foo" match {
  case v if v != null => doSomethingWith v
}

but this causes a MatchError if the properties object does not contain foo.

I can think of two ways to tackle this. Approach 1 is:

myProps getProperty "foo" match {
  case v if v != null => doSomethingWith v
  case _ => // ignore if foo does not exist
}

Approach 2 is:

if(myProps containsKey "foo") doSomethingWith(myProps getProperty "foo")

Personally, I like approach 1 better because it queries the Properties only once and the comment tells that a non-match is intentionally ignored, but this is also quite verbose. Approach 2 has the flaw that, besides from querying the Properties twice, if in the near future the key is changed, it has to be changed at two places here which is a source of bugs.

So, is there a better way to do it like approach 1, but shorter, or is this the way it is done?

Upvotes: 0

Views: 71

Answers (1)

mohit
mohit

Reputation: 4999

Try wrapping your function in Option.

Option(myProps getProperty "foo").map {
    v => doSomethingWith v
}

Option(myProps getProperty "foo") will return either Some(propertyValue) or None. Only if the result is Some(propertyValue), doSomethingWith (v) in the code will be executed. If it is None, it will be ignored.

You can also have a default value in case the result is None by using getOrElse function on the Option.

As mentioned in comments by @VladimirMatveev, map is not the right thing to do, if the method doSomethingWith has side effects. Use foreach instead.

Upvotes: 3

Related Questions