突破特定集合类型的捷径?
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))
有更短的方法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以通过从返回类型推断出
breakOut
的类型参数来使其更加简洁:You can make it a bit more concise by letting the type parameters to
breakOut
be inferred from the return type:虽然 Ben 的答案是正确的,但另一种选择是使用类型别名:
Whilst Ben's is the correct answer, an alternative would have been to use a type alias:
结合 Ben 和 oxbow_lakes 的答案,你可以得到更短的内容:
Combining Ben and oxbow_lakes' answers, you can get a little shorter still: