Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing functions of tuples conveniently in Scala

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?

like image 885
Alexey Romanov Avatar asked Jun 02 '10 11:06

Alexey Romanov


3 Answers

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) }
like image 169
Ben Lings Avatar answered Nov 05 '22 21:11

Ben Lings


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.

like image 21
mkneissl Avatar answered Nov 05 '22 20:11

mkneissl


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)}
like image 5
RoToRa Avatar answered Nov 05 '22 21:11

RoToRa