I have a list like this:
val objectKeys = List("Name","Place","Animal","Thing");
I want to reduce it to a Map[String,Boolean] where Boolean is element.size < 8
.
Here's what I wrote:
val mappedObject = objectKeys.fold(Map[String,Boolean])((map,key) => map + (key -> key.size < 8))
which gives me the following error:
value + is not a member of Object, but could be made available as an extension method.
and
value size is not a member of Object
My understanding about fold is that it takes a default argument and reduces the entire value around it which however doesn't seem to work in this case. Can anyone help me with this?
Ideally mappedObject should be like:
val mappedObject = Map[String,Boolean]("Name"->true,"Place"->true,"Animal"->true,"Thing"->true)
An equivalent Javascript implementation will be:
const listValues = ["Name","Place","Animal","Thing"];
const reducedObject = listValues.reduce((acc,curr) => {acc[curr] = curr.length < 8;
return acc;
},{});
I think in this case you should just map
to a tuple containing your key with boolean check and then convert it to Map[String, Boolean]
via toMap
method as following.
objectKeys.map(key => (key, key.length < 8)).toMap
If you really want to do it with a fold, that's easy to do:
objectKeys.foldLeft(Map.empty[String, Boolean]) { (acc, key) =>
acc + ((key, key.length < 8))
}
That said, I'm with Ivan on this one. map
is clearly the better solution here (or fproduct
if you're using the cats library).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.