Reputation: 18036
Is there a shorter way to doing this:
val accessControlAllowOrigin = c_dash.getString("access-control-allow-origin") match {
case "" => None
case x => Some(x)
}
This is reading in a Typesafe Config value, where empty string denotes the absence of such a config (in Typesafe Config it's good manners to include all values, not leaving anything out).
Is there something like:
val sopt = Option( s, "magic" )
..which would provide either Some(s)
or None
if s
's value is "magic"
?
By looking at the doc I came to:
scala> def f(s: String) = (Some(s) filter( _ != "magic" ))
f: (s: String)Option[String]
scala> f("aaa")
res1: Option[String] = Some(aaa)
scala> f("magic")
res2: Option[String] = None
Is that the simplest?
Upvotes: 1
Views: 426
Reputation: 41749
I may be missing something obvious, but how about:
val sopt = if (s == "magic") None else Some(s)
Or, for your f():
def f(s:String) = if (s == "magic") None else Some(s)
or, more generically:
def noneIfDefault(s:String, default: String) = if (s == default) None else Some(s)
Upvotes: 2
Reputation: 55569
You can use filter
, which works the same for an Option
as it would for any other collection:
c_dash.getString("access-control-allow-origin").filter(_.nonEmpty)
Anything not matching the filter
predicate will become None
.
Upvotes: 5