作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有:
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)) }
}
}
第一行编译正常,测试通过。如果我用注释掉的第二行替换第一行,我会得到一个编译错误。
found : (String, Int) => Unit, required: ((String, Int)) => Unit
类型不匹配,预期:((String, Int)) => 单位,实际:(String, Int) => 单位
这是为什么?我该如何解决?
最佳答案
您正在使用的方法接受一个将单个 参数转换为单个输出的函数。您在第二个语句中告诉 Scala 的是 map 应该接受带有两个参数的函数! 单个参数恰好是大小为 2 的元组,与两个不同的参数之间存在重要区别。
所以你只有一个参数,但你(和 Scala)知道它是一个元组。要访问这两个元素,您必须解构 或模式匹配 反对您想要的元组的论点。您只需编写 forAll (map) { case (k: String, v: Int) => assert(v === expected(k)) }
即可。您是说您收到的参数应该匹配元组 (String, Int)
的模式,并且您希望第一个元素绑定(bind)到 k
,第二个元素绑定(bind)到 v
。您可能无需在此处明确提及类型。请注意,这类似于模式匹配中使用的语法,本质上就是您在此处所做的。
关于scala - Scala 中令人困惑的类型不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24036569/
我是一名优秀的程序员,十分优秀!