9

I'm having a real brain fart here. I'm working with the Play Framework. I have a method which takes a map and turns it into a HTML select element. I had a one-liner to take a list of objects and convert it into a map of two of the object's fields, id and name. However, I'm a Java programmer and my Scala is weak, and I've only gone and forgotten the syntax of how I did it.

I had something like

organizations.all.map {org => /* org.prop1, org.prop2 */ }

Can anyone complete the commented part?

evanjdooner
  • 884
  • 1
  • 5
  • 24

2 Answers2

15

I would suggest:

map { org => (org.id, org.name) } toMap

e.g.

scala> case class T(val a : Int, val b : String)
defined class T

scala> List(T(1, "A"), T(2, "B"))
res0: List[T] = List(T(1,A), T(2,B))

scala> res0.map(t => (t.a, t.b))
res1: List[(Int, String)] = List((1,A), (2,B))

scala> res0.map(t => (t.a, t.b)).toMap
res2: scala.collection.immutable.Map[Int,String] = Map(1 -> A, 2 -> B)
Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
6

You could also take an intermediary List out of the equation and go straight to the Map like this:

case class Org(prop1:String, prop2:Int)
val list = List(Org("foo", 1), Org("bar", 2))  
val map:Map[String,Int] = list.map(org => (org.prop1, org.prop2))(collection.breakOut)

Using collection.breakOut as the implicit CanBuildFrom allows you to basically skip a step in the process of getting a Map from a List.

cmbaxter
  • 35,283
  • 4
  • 86
  • 95
  • 1
    I found your answer here really interesting, I'd never heard of breakOut... fyi a little more reference information for those also learning: http://stackoverflow.com/questions/1715681/scala-2-8-breakout – LaloInDublin Aug 19 '13 at 16:29
  • Thanks for the suggestion. However, I tried to use a variant of your line `list.map(org => (org.prop1, org.prop2))(collection.breakOut)` in a scala html template but it returns an object of type `scala.collection.immutable.IndexedSeq[(String, String)`. The code I've used is `Organization.all.map(org => (org.id.toString, org.name))(collection.breakOut)` where `Organization.all()` is a Java method that returns a `List`. – evanjdooner Aug 22 '13 at 11:39
  • 1
    @evanjdooner, did you type the val or var you were assigning the result to. It must be explicitly typed for it to end up as a Map as my example shows. – cmbaxter Aug 22 '13 at 17:32
  • Ah, I see. I omitted the variable assignment as I was passing it as a parameter. I'll try it your way. – evanjdooner Aug 23 '13 at 08:25