Eclipse上的Scala在Map操作上给出了错误

时间:2016-06-09 23:48:36

标签: eclipse scala

我正在尝试使用Scala中的Maps编写一个单词Count计划。从互联网上的各种来源,我发现'包含',使用'+'向地图添加元素并更新现有值是有效的。但是当我尝试在我的代码中使用这些操作时,Eclipse给了我错误:

object wc {

 def main(args:Array[String])={
  val story = """ Once upon a time there was a poor lady with a son who was lazy
                  she was worried how she will grow up and
                  survive after she goes """

  count(story.split("\n ,.".toCharArray()))

 }

 def count(s:Array[String])={

    var count = scala.collection.mutable.Map
    for(i <- 0 until s.size){
     if(count.contains(s(i))) {
       count(s(i)) = count(s(i))+1

     }
     else count = count + (s(i),1)
    } 
    println(count)

 }
}

这些是我在eclipse中收到的错误消息: 1.)enter image description here

2。)enter image description here

3。)enter image description here

我在REPL上尝试了这些操作,它们工作正常,没有任何错误。任何帮助,将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:2)

您需要实例化一个类型化的可变Map(否则您正在寻找Map.type上的contains属性;哪个不存在):

 def count(s: Array[String]) ={
   var count = scala.collection.mutable.Map[String, Int]()
   for(i <- 0 until s.size){
     if (count.contains(s(i))) {
       // count += s(i) -> (count(s(i)) + 1)
       // can be rewritten as
       count(s(i)) += 1    
     }
     else count += s(i) -> 1
   }
   println(count)
}

注意:我还修改了更新计数行。

也许这更好地写成一个群体:

a.groupBy({s: String => s}).mapValues(_.length)

val a = List("a", "a", "b", "c", "c", "c")

scala> a.groupBy({s: String => s}).mapValues(_.length)
Map("b" -> 1, "a" -> 2, "c" -> 3): Map[String, Int]