4

I've got a query result of List[(Int,String,Double)] that I need to convert to a Map[String,String] (for display in an html select list)

My hacked solution is:

val prices = (dao.getPricing flatMap {
  case(id, label, fee) =>
    Map(id.toString -> (label+" $"+fee))
  }).toMap

there must be a better way to achieve the same...

2 Answers 2

9

How about this?

val prices: Map[String, String] =
  dao.getPricing.map {
    case (id, label, fee) => (id.toString -> (label + " $" + fee))
  }(collection.breakOut)

The method collection.breakOut provides a CanBuildFrom instance that ensures that even if you're mapping from a List, a Map is reconstructed, thanks to the type annotation, and avoids the creation of an intermediary collection.

Sign up to request clarification or add additional context in comments.

3 Comments

+1. odd, what on earth is collection.breakout? ;-) I like that Map has been removed from the map{} block, but now it's been added to the return type ;-(, compiler inference rocks, no like type type type, that's for Java people ;-)
@virtualeyes Either you write toMap and you have to create an intermediary collection, or you use breakOut with the type annotation.
@Jean-Phillipe ah ok, so my approach is not only poor, but inefficient as well ;-) No big deal here, pricing consists of a handful of records, any which way does the trick, was just looking for a cleaner solution than what I had hacked together
8

A little more concise:

val prices =
  dao.getPricing.map { case (id, label, fee) => ( id.toString, label+" $"+fee)} toMap

shorter alternative:

val prices =
  dao.getPricing.map { p => ( p._1.toString, p._2+" $"+p._3)} toMap

7 Comments

there you go, nice one, +1, plus a prize, concision is king
+1 for first alternative, -1 to the second ... giving things names is at lot more readable than p._1 etc. (Although virtualeyes might consider making the dao return a Pricing case class rather than using a triple, in which case the second option would be fine).
I agree, I prefer it, too. Just added for reference.
@MattR you're right, using ScalaQuery, could just as well return a case class instance, but thought I'd explore tuples (since vast majority of query results are cast to case class instances, quite convenient)
@MattR I switched to case class instance, the cleanest approach, and minimal extra overhead compared to returning a tuple subset
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.