I’d like to build a Map like this:
def one = "one"
def two = "two"
def three = Some("three")
Map[String, String]("one" -> one, "two" -> two, "three" -> three)
This won’t compile because the method three returns an Option instead of a String.
I can make this work like this:
Map[String, String]("one" -> one, "two" -> two) ++ three.map(t => Map("three" -> t)).getOrElse(Map.empty[String, String])
Now it will only add the Option to the list when it’s Some.
But there must be a more elegant way. (lift-json for example knows how to filter out Options when constructing JValue’s).
Any suggestions?
(P.S. I’ve simplified the problem here)
In order to provide a nice interface to your clients, you could extend one of the
Map‘s to perform the unpacking:Combine this with an implicit that turns pairs
(A, B)into pairs(A, Option[B]):And use it as: