views:

296

answers:

6

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?

+2  A: 
Arjan Blokzijl
Yes, forgot to add that alternative. But I don't like it, because in this case the fields of tuple do have actual meaning (key and value) and I want to reflect it in my code.
Alexey Romanov
A: 

I was pretty close with the last attempt, actually:

> map.foreach({case (k, v) => println(k)})
1
3
Alexey Romanov
+10  A: 

You were very close with map.foreach(case (k, v) => println(k)). To use case in an anonymous function, surround it by curly brackets.

map foreach { case (k, v) => println(k) }
Ben Lings
+2  A: 
Welcome to Scala version 2.8.0.Beta1-prerelease (OpenJDK Server VM, Java 1.6.0_0).
Type in expressions to have them evaluated.
Type :help for more information.

scala> val m = Map('a -> 'b, 'c -> 'd)
m: scala.collection.immutable.Map[Symbol,Symbol] = Map('a -> 'b, 'c -> 'd)

scala> m foreach { case(k, v) => println(k) }
'a
'c
missingfaktor
A: 

One alternative is the tupled method of the Function object:

import Function.tupled;
// map tupled foreach {(k, v) => println(k)}
map foreach tupled {(k, v) => println(k)}
RoToRa
Does not work .
missingfaktor
@Rahul `map foreach Function.tupled((k,v) => println(k))` or `map foreach ((k : Int,v : Int) => println(k)).tupled` does.
Thomas Jung
@Thomas, Oh, didn't know that. Thanks.
missingfaktor
Yes, sorry I accidently swapped `tupled` and the function call. I'll change it.
RoToRa
+2  A: 

In such cases I often use the for syntax.

for ((k,v) <- map) println(k)

According to Chapter 23 in "Programming in Scala" the above for loop is translated to call foreach.

mkneissl