breakOut到特定集合类型的简短方法?

时间:2010-04-07 11:36:24

标签: scala scala-2.8 scala-collections

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

我想要的是结果类型是List [(Int,Int,Int)]。我发现的唯一方法是:

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

有更短的路吗?

3 个答案:

答案 0 :(得分:12)

您可以通过从返回类型推断类型参数breakOut来使其更简洁:

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

答案 1 :(得分:6)

虽然Ben是正确答案,但另一种方法是使用类型别名

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

答案 2 :(得分:0)

结合Ben和oxbow_lakes的答案,你可以缩短一点:

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