Writing functions of tuples conveniently in Scala

Posted by Alexey Romanov on Stack Overflow See other posts from Stack Overflow or by Alexey Romanov
Published on 2010-06-02T11:35:59Z Indexed on 2010/06/02 11:54 UTC
Read the original article Hit count: 214

Filed under:
|

Quite a few functions on Map take a function on a key-value tuple as the argument. E.g. def foreach(f: ((A, B)) ? Unit): Unit. So I looked for a short way to write an argument to foreach:

> val map = Map(1 -> 2, 3 -> 4)

map: scala.collection.immutable.Map[Int,Int] = Map(1 -> 2, 3 -> 4)

> map.foreach((k, v) => println(k))

error: wrong number of parameters; expected = 1
       map.foreach((k, v) => println(k))
                          ^

> map.foreach({(k, v) => println(k)})

error: wrong number of parameters; expected = 1
       map.foreach({(k, v) => println(k)})
                           ^

> map.foreach(case (k, v) => println(k))

error: illegal start of simple expression
       map.foreach(case (k, v) => println(k))
                   ^

I can do

> map.foreach(_ match {case (k, v) => println(k)})

1
3

Any better alternatives?

© Stack Overflow or respective owner

Related posts about scala

Related posts about scala-2.8