What is the proper way of doing partial matches in Scala? -
i have properties
object, , want if configuration contains specific key. if key not exist, want ignore it. tried following way:
myprops getproperty "foo" match { case v if v != null => dosomethingwith v }
but causes matcherror
if properties object not contain foo
.
i can think of 2 ways tackle this. approach 1 is:
myprops getproperty "foo" match { case v if v != null => dosomethingwith v case _ => // ignore if foo not exist }
approach 2 is:
if(myprops containskey "foo") dosomethingwith(myprops getproperty "foo")
personally, approach 1 better because queries properties
once , comment tells non-match intentionally ignored, quite verbose. approach 2 has flaw that, besides querying properties
twice, if in near future key changed, has changed @ 2 places here source of bugs.
so, there better way approach 1, shorter, or way done?
try wrapping function in option
.
option(myprops getproperty "foo").map { v => dosomethingwith v }
option(myprops getproperty "foo")
return either some(propertyvalue)
or none
. if result some(propertyvalue)
, dosomethingwith (v)
in code executed. if none, ignored.
you can have default value in case result none using getorelse
function on option
.
as mentioned in comments @vladimirmatveev, map
not right thing do, if method dosomethingwith
has side effects. use foreach
instead.
Comments
Post a Comment