[英]What's wrong with this piece of scala code?
我有以下無法編譯的代碼片段:
val cids = List(1, 2, 3, 4)
val b = Map.newBuilder[Int, Int]
for (c <- cids) {
b += (c, c*2)
}
b.result()
編譯器報告說
console>:11: error: type mismatch;
found : Int
required: (Int, Int)
b += (c, c*2)
我不知道有什么錯誤。
這會起作用:
for (c <- cids) {
b += ((c, c*2))
}
括號被編譯器解析為+=
函數的參數列表括號,而不是元組。 添加嵌套括號意味着將元組作為參數傳遞。 這是混淆...
您可以通過以下方式修復它:
b += (c->c*2)
這是一個重復的問題。
通常,提供非元組 arg 列表的工作方式如圖所示,但是當方法重載時它不起作用,因為它會選擇您不打算使用的方法,並且不會費心嘗試自動調整您的 args。
scala> class C[A] { def f(a: A) = 42 }
defined class C
scala> val c = new C[(String, Int)]
c: C[(String, Int)] = C@3a022576
scala> c.f("1", 1)
res0: Int = 42
scala> class C[A] { def f(a: A) = 42 ; def f(a: A, b: A, rest: A*) = 17 }
defined class C
scala> val c = new C[(String, Int)]
c: C[(String, Int)] = C@f9cab00
scala> c.f("1", 1)
<console>:14: error: type mismatch;
found : String("1")
required: (String, Int)
c.f("1", 1)
^
一種使用(不可變)值的方法,
(cids zip cids.map(_ * 2)).toMap
使用zip
我們將每個值與其雙zip
配對,並將結果列表轉換為Map
。
如果你去文檔你會發現:這個
支持的 API 是ms += (k -> v)
。 那是你需要使用
for (c <- cids) {
b += (c -> c*2)
}
或者,您可以使用上面建議的((c, c*2))
語法。 發生這種情況是因為編譯器無法知道括號是用於元組的。 它只是將該參數理解為傳遞給 += 方法的兩個參數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.