Reputation: 27
I have a method as follows:
protected def extract(implicit params:Params) =
Map(
"address" -> params.address,
"city" -> params.address,
"region" -> params.region,
)collect {
case (k, v) if v.isDefined => k -> v.get
}
I want to substitute value of city such that :
"city" -> if(params.city.contains("York")) "NewYork" else params.city,
How can I achieve this in scala?
Upvotes: 0
Views: 77
Reputation: 7735
Small correction to Bruce answer
myMap.collect {
case ("city", Some(city)) if(city.contains("York")) => "NewYork"
case (k, v) if v.isDefined => k -> v.get
}
Would not result in a Map, but an Iterable
myMap.collect {
case ("city", Some(city)) if(city.contains("York")) => "city" -> "NewYork"
case (k, Some(v)) => k -> v
}
Would be better
Upvotes: 0
Reputation: 6193
Stephens approach of just creating the map with the correct value is probably best. If you've got a general map, of what appears to be String to Option[String], and want to substitute the city key if the value contains York, then this will work as well.
myMap.collect {
case ("city", Some(city)) if(city.contains("York")) => "NewYork"
case (k, v) if v.isDefined => k -> v.get
}
Upvotes: 1
Reputation: 4296
You could put it in line
def extract(implicit params:Params) =
Map(
"address" -> params.address,
"city" -> (if(params.city.contains("York")) Some("NewYork") else params.city),
"region" -> params.region
) collect {
case (k, v) if v.isDefined => k -> v.get
}
Im sure there are lots of other way to do it. Not sure what your really after.
Upvotes: 1