Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala - can a lambda parameter match a tuple?

Tags:

scala

So say i have some list like

val l = List((1, "blue"), (5, "red"), (2, "green")) 

And then i want to filter one of them out, i can do something like

val m = l.filter(item => {     val (n, s) = item          // "unpack" the tuple here     n != 2 } 

Is there any way i can "unpack" the tuple as the parameter to the lambda directly, instead of having this intermediate item variable?

Something like the following would be ideal, but eclipse tells me wrong number of parameters; expected=1

val m = l.filter( (n, s) => n != 2 ) 

Any help would be appreciated - using 2.9.0.1

like image 973
dvmlls Avatar asked Aug 23 '11 15:08

dvmlls


1 Answers

This is about the closest you can get:

 val m = l.filter { case (n, s) => n != 2 } 

It's basically pattern matching syntax inside an anonymous PartialFunction. There are also the tupled methods in Function object and traits, but they are just a wrapper around this pattern matching expression.

like image 172
Kipton Barros Avatar answered Sep 19 '22 23:09

Kipton Barros