Scala Map foreach

后端 未结 7 1968
刺人心
刺人心 2021-01-31 14:15

given:

val m = Map[String, Int](\"a\" -> 1, \"b\" -> 2, \"c\" -> 3)
m.foreach((key: String, value: Int) => println(\">>> key=\" + key + \",          


        
7条回答
  •  庸人自扰
    2021-01-31 14:39

    I'm not sure about the error, but you can achieve what you want as follows:

    m.foreach(p => println(">>> key=" + p._1 + ", value=" + p._2))
    

    That is, foreach takes a function that takes a pair and returns Unit, not a function that takes two arguments: here, p has type (String, Int).

    Another way to write it is:

    m.foreach { case (key, value) => println(">>> key=" + key + ", value=" + value) }
    

    In this case, the { case ... } block is a partial function.

提交回复
热议问题