您可以使用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