user12019412
user12019412

Reputation:

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

Upvotes: 2

Views: 168

Answers (2)

Volty De Qua
Volty De Qua

Reputation: 288

Just for the sake of playing with transformations:

def to1[A, B](f: () => B): A => B = (_: A) =>  f()

val a = new Array[Int](5)
def f(): Int = 1
a.map(to1(f))

Regarding your example, consider using fill:

val b = Array.fill[Int](a.size)(myArgLessFunc())

Upvotes: 0

Mario Galic
Mario Galic

Reputation: 48420

Try using underscore for ignored argument like so

a.map(_ => f)

which outputs

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

Upvotes: 1

Related Questions