short way to breakOut to specific collection type?

醉酒当歌 提交于 2019-12-19 06:03:53

问题


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?


回答1:


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))



回答2:


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]])



回答3:


Combining Ben and oxbow_lakes' answers, you can get a little shorter still:

type I3 = (Int, Int, Int)
m.map {case (a, b) ⇒ (a+1, a+2, a+3)}(breakOut): List[I3]


来源:https://stackoverflow.com/questions/2592024/short-way-to-breakout-to-specific-collection-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!