您可以使用breakOut
确保没有创建中间集合。例如:
// creates intermediate list.
scala> List((3, 4), (9, 11)).map(_.swap).toMap
res542: scala.collection.immutable.Map[Int,Int] = Map(4 -> 3, 11 -> 9)
scala> import collection.breakOut
import collection.breakOut
// doesn't create an intermediate list.
scala> List((3, 4), (9, 11)).map(_.swap)(breakOut) : Map[Int, Int]
res543: Map[Int,Int] = Map(4 -> 3, 11 -> 9)
您可以阅读更多关于它here。
UPDATE:
如果你读的breakOut
的定义,你会发现它基本上创建预期类型的CanBuildFrom
对象,并明确地传递给该方法的一种方式。 breakOut
仅仅可以避免输入以下样板。
// Observe the error message. This will tell you the type of argument expected.
scala> List((3, 4), (9, 11)).map(_.swap)('dummy)
<console>:16: error: type mismatch;
found : Symbol
required: scala.collection.generic.CanBuildFrom[List[(Int, Int)],(Int, Int),?]
List((3, 4), (9, 11)).map(_.swap)('dummy)
^
// Let's try passing the implicit with required type.
// (implicitly[T] simply picks up an implicit object of type T from scope.)
scala> List((3, 4), (9, 11)).map(_.swap)(implicitly[CanBuildFrom[List[(Int, Int)], (Int, Int), Map[Int, Int]]])
// Oops! It seems the implicit with required type doesn't exist.
<console>:16: error: Cannot construct a collection of type Map[Int,Int] with elements of type (Int, Int) based on a coll
ection of type List[(Int, Int)].
List((3, 4), (9, 11)).map(_.swap)(implicitly[CanBuildFrom[List[(Int, Int)], (Int, Int), Map[Int, Int]]])
// Let's create an object of the required type ...
scala> object Bob extends CanBuildFrom[List[(Int, Int)], (Int, Int), Map[Int, Int]] {
| def apply(from: List[(Int, Int)]) = foo.apply
| def apply() = foo.apply
| private def foo = implicitly[CanBuildFrom[Nothing, (Int, Int), Map[Int, Int]]]
| }
defined module Bob
// ... and pass it explicitly.
scala> List((3, 4), (9, 11)).map(_.swap)(Bob)
res12: Map[Int,Int] = Map(4 -> 3, 11 -> 9)
// Or let's just have breakOut do all the hard work for us.
scala> List((3, 4), (9, 11)).map(_.swap)(breakOut) : Map[Int, Int]
res13: Map[Int,Int] = Map(4 -> 3, 11 -> 9)
哇,这真的需要542名试图获得这种权利;-) –
谢谢,这正是我一直在寻找。什么我不知道的是,为什么斯卡拉抱怨'名单((3,4),(9,11))地图(_交换):使用类型约束我有地图[INT,INT]'代替。明确地选择正确的隐式(正如read所示,根据上下文在haskell中选择正确的类型实例)。难道这只是隐含的不以这种方式工作(我会完全理解它,我知道子类型会使一切都变得困难),还是我忽略了这种特殊情况下的某些东西? –
@DuncanMcGregor:我过去5天没有关闭REPL。我在日常的开发中大量使用它。 :-) – missingfaktor