我编写了简单的代码,它将不可变的字符映射及其索引作为vector:
返回def indexes(string: String): Map[Char, Vector[Int]] = (0 until string.length).
foldLeft(Map[Char, Vector[Int]]()){
(m, i) => m + (string(i) -> m.getOrElse(string(i), Vector()).:+(i))
}
例如:
println(indexes("Mississippi"))
// Map(M -> Vector(0), i -> Vector(1, 4, 7, 10), s -> Vector(2, 3, 5, 6), p -> Vector(8, 9))
为什么Scala不能推断m.getOrElse(string(i), Vector()) :+ i
是Vector[Int]
并编译它?我应该写m.getOrElse(string(i), Vector()).:+(i)
代替。
答案 0 :(得分:1)
使用带括号的Map值可以正常工作:
def indexes(string: String): Map[Char, Vector[Int]] = (0 until string.length).
foldLeft(Map[Char, Vector[Int]]()){
(m, i) => m + (string(i) -> (m.getOrElse(string(i), Vector()) :+ i))
}
indexes("Mississippi")
// res1: Map[Char,Vector[Int]] = Map(M -> Vector(0), i -> Vector(1, 4, 7, 10), s -> Vector(2, 3, 5, 6), p -> Vector(8, 9))
如果不对Map值进行括号,则下面代码的(k -> a :+ b)
键值部分将被视为(k -> a) :+ b
,从而导致编译错误:
(m, i) => m + (string(i) -> m.getOrElse(string(i), Vector()) :+ i)
// <console>:28: error: value :+ is not a member of (Char, Vector[Int])