Reputation: 2908
I have the following map Map(FULL -> 3854.0, REMAINING -> 3769.0)
I would like to compute the two values such that the (FULL/REMAINING)*100
Is there an good way to do this? I tried m.foldLeft(0)(_/_._2)
but the compilier is complaining about a type mismatch between float and Int?
Upvotes: 0
Views: 92
Reputation: 24403
With a Map, there is no guarantee, that the two value are really present. So you may want to create a class for that, as Ken Bloom already suggested, or do it with the get
method of Map
, which returns an Option[B]
:
val resOpt = for {
full <- m.get("FULL")
remainig <- m.get("REMAINING")
} yield (full / remaining) * 100
resOpt.getOrElse(someDefaultValue)
This way you avoid nasty runtime errors.
Upvotes: 1
Reputation: 58790
You can fix the type mismatch by specifying 0.0
as the first argument to foldLeft
, but that won't make your code right. It will then compute 0.0/3854.0/3769.0
which equals 0.0
.
In fact, Map(FULL -> 3854.0, REMAINING -> 3769.0)
is not guaranteed to be ordered, so I'm pretty sure the best you can do is m('FULL') / m('REMAINING')
.
Perhaps you want to create a case class
for this instead, in which case you could just say m.full/m.remaining
or even make a method to compute that automatically.
Upvotes: 4