开发者

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?


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) }


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.


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)}


You can also access a tuple as follows:


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


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


I was pretty close with the last attempt, actually:

> map.foreach({case (k, v) => println(k)})
1
3
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜