Wade Jensen Wade Jensen - 25 days ago 10
Scala Question

Pass input to map lambda as tuple in Scala

I'm trying to find a concise way of passing the result of zipping two arrays into a map function, ie. one that does not require declaring both the input variables and using a fat arrow in the lambda.

This may not even be possible, but I thought I'd ask before giving up.

The first example is working code that prints the result of adding both arrays element-wise. The lambda for the zip has to declare x and y before they can be used.

The second example is non-compiling code which illustrates what I would like to do using "_" or similar to give the transformation function better usability for zipped inputs.

Example 1

object Example extends App {

val numbers1: Array[Int] = Array(1,2,3,4,5)
val numbers2: Array[Int] = Array(9,8,7,6,5)

val result = (numbers1, numbers2).zipped.map( (x,y) => sum(x,y) )

result.foreach( println(_) )

def sum(x: Int, y: Int): Int = {
x+y
}
}


This is fine when the transformation function has a short name like "sum" and the input arrays are of primitives, but things get more verbose when passing in an array of wrapper objects which contain several member variables the transformation requires as arguments.

Is there a syntactic sugar which allows something like this: ?

Example 2

object Example extends App {

val numbers1: Array[Int] = Array(1,2,3,4,5)
val numbers2: Array[Int] = Array(9,8,7,6,5)

val result = (numbers1, numbers2).zipped.map( sum(_) )

result.foreach( println(_) )

def sum( inputTuple: (Int, Int) ): Int = {
val x = inputTuple._1
val y = inputTuple._2
x + y
}
}


The more I detail this the more I feel like I've written myself into code smell, so if thats the answer please say so and I'll go solve the problem from another direction.

Answer Source

You can just...

val result = (numbers1, numbers2).zipped.map(sum)

... or even slicker ...

val result = numbers1 zip numbers2 map sum

It's also worth noting that this format allows for a more natural argument list in the sum() method.

def sum(x:Int, y: Int): Int = x + y