Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

short way to breakOut to specific collection type?

scala> val m = Map(1 -> 2)
m: scala.collection.immutable.Map[Int,Int] = Map(1 -> 2)

scala>  m.map{case (a, b) => (a+ 1, a+2, a+3)}
res42: scala.collection.immutable.Iterable[(Int, Int, Int)] = List((2,3,4))

What I want is for the result type to be List[(Int, Int, Int)]. The only way I found is:

scala>  m.map{case (a, b) => (a+ 1, a+2, a+3)}(breakOut[Map[_,_], (Int, Int, Int), List[(Int, Int, Int)]])
res43: List[(Int, Int, Int)] = List((2,3,4))

Is there a shorter way?

like image 745
IttayD Avatar asked Apr 07 '10 11:04

IttayD


2 Answers

You can make it a bit more concise by letting the type parameters to breakOut be inferred from the return type:

scala>  m.map{case (a, b) => (a+1, a+2, a+3)}(breakOut) : List[(Int, Int, Int)]
res3: List[(Int, Int, Int)] = List((2,3,4))
like image 135
Ben Lings Avatar answered Oct 10 '22 20:10

Ben Lings


Whilst Ben's is the correct answer, an alternative would have been to use a type alias:

type I3 = (Int, Int, Int)
m.map{case (a, b) => (a+ 1, a+2, a+3)}(breakOut[Map[_,_], I3, List[I3]])
like image 26
oxbow_lakes Avatar answered Oct 10 '22 22:10

oxbow_lakes