【发布时间】:2014-06-04 11:48:08
【问题描述】:
我有:
val words = List("all", "the", "words", "all", "the", "counts", "all", "day")
val map = Exercise02.count(words.iterator)
val expected = Map("all" -> 3, "the" -> 2, "words" -> 1, "counts" -> 1, "day" -> 1)
其中Exercise02.count 是java.util.Iterator[String] => Map[String, Int] 并且仅生成输入java.util.Iterator[String] 中每个单词的计数。
我写了一个测试:
object Exercise02Spec extends FlatSpec with Inspectors {
val words = List("all", "the", "words", "all", "the", "counts", "all", "day")
val map = Exercise02.count(words.iterator)
val expected = Map("all" -> 3, "the" -> 2, "words" -> 1, "counts" -> 1, "day" -> 1)
"count" should "count the occurrence of each word" in {
forAll (map) { kv => assert(kv._2 === expected(kv._1)) }
// forAll (map) { (k: String, v: Int) => assert(v === expected(k)) }
}
}
第一行编译得很好,测试通过了。如果我将第一行替换为已注释掉的第二行,则会出现编译错误。
- sbt 报告:
found : (String, Int) => Unit, required: ((String, Int)) => Unit - IntelliJ IDEA 报告:
Type mismatch, expected: ((String, Int)) => Unit, actual: (String, Int) => Unit
这是为什么?我该如何解决?
【问题讨论】:
-
How to iterate scala map? 的可能重复项
-
在将映射值匹配到元组时,您似乎缺少
case。试试forAll (map) { case (k: String, v: Int) => assert(v === expected(k)) }。有什么理由不只是检查assert(map == expected)的地图是否相等? -
因为一旦我走上这条路,我想了解为什么
(k: String, v: Int) => assert(v === expected(k))是不可接受的。 :-)