arraysscalamap-functionarity

How to apply a 0-ary anonymous function to an array


Having an Array of Int, and a function without parameters:

scala> val a = new Array[Int](5)
a: Array[Int] = Array(0, 0, 0, 0, 0)

scala> def f(): Int = 1
f: ()Int

I want to apply the function f() to the array with map() or transform(). I tried the following approaches.

First approach

scala> a.map(f)
<console>:14: error: type mismatch;
 found   : () => Int
 required: Int => ?
       a.map(f)
             ^

It fails, which I don't really understand why.

Second approach

scala> a.map(x => f)
res1: Array[Int] = Array(1, 1, 1, 1, 1)

This one works. However, I'm declaring a parameter x that I don't use in the right side of =>. It seems that anonymous functions need at least one parameter.

Practical example

To give an example on why one would use that. Imagine I have an array that at some moment I want to mutate to have random values:

val a = new Array[Int](5)
// ...
a.transform(x => random())

Solution

  • Try using underscore for ignored argument like so

    a.map(_ => f)
    

    which outputs

    res0: Array[Int] = Array(1, 1, 1, 1, 1)