I’m using an api that I can’t change that returns a 2-element map where one key is always present but the other key/value pair is dynamic, and I’m trying to unpack them into a case class. The code below works, but is really ugly:
case class Foo(name: String, key: String, value: String)
def fooFromMap(item: Map[String, String]): Option[Foo] = {
var name: String = null
var key: String = null
var value: String = null
item.foreach {
case ("name", v) => name = v
case (k, v) => key = k; value = v
}
if(name != null && key != null && value != null) Some(Foo(name, key, value))
else None
}
Is there a nicer way to do this?
The following is equivalent, and more idiomatic:
If either
item get "name"or(item - "name").headOptioncomes up empty, the result will be empty—otherwise you get theFooyou want.