Scala Map foreach

后端 未结 7 1950
刺人心
刺人心 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:52

    Excellent question! Even when explicitly typing the foreach method, it still gives that very unclear compile error. There are ways around it, but I can't understand why this example does not work.

    scala> m.foreach[Unit] {(key: String, value: Int) => println(">>> key=" + key + ", value=" + value)}
    :16: error: type mismatch;
     found   : (String, Int) => Unit
     required: (String, Int) => Unit
                  m.foreach[Unit] {(key: String, value: Int) => println(">>> key=" + key + ", value=" + value)}
                                                             ^
    

提交回复
热议问题