0

How can this be automated? (Insert the elements of the array into the arguments of the function)


def func(d1: Boolean, d2: Boolean, d3: Boolean, d4: Boolean) = ???

val data = Array(true, true, false, false)

func(
  data(0),
  data(1),
  data(2),
  data(3)
)
Daedro
  • 1
  • Scala has an `apply` method that does this doesn't it? In most languages (that I know at least), the function that achieves this is called `apply`. – Carcigenicate Jul 15 '17 at 15:35
  • @Carcigenicate `apply` is used for `object`s (types, really). One could create a helper object that does something similar to tuple unwrapping in Python, but otherwise this isn't going to get much cleaner. – erip Jul 15 '17 at 15:43

4 Answers4

2

If I undestand your question correctly:

def func(d: Boolean*) = {
  d.map( if (_) "yes" else "no" ).foreach(println)
}

val data = Array(true, true, false, false)

func(data: _*)
yes
yes
no
no
Leo C
  • 22,006
  • 3
  • 26
  • 39
1

You can use the 'splat' operator with a varargs argument:

def func(args : Boolean*) = {
  args foreach println
}

val data = Array(true, true, false, false)

func(data: _*)
sheunis
  • 1,494
  • 11
  • 10
0

If you manage to convert your list to a tuple:

scala> def func(d1: Boolean, d2: Boolean, d3: Boolean, d4: Boolean) = s"$d1 $d2 $d3 $d4"
func: (d1: Boolean, d2: Boolean, d3: Boolean, d4: Boolean)String

scala> val ff = func _
ff: (Boolean, Boolean, Boolean, Boolean) => String = $$Lambda$1151/1744486549@5a13f1f7

scala> val data = (true,false,true,true)
data: (Boolean, Boolean, Boolean, Boolean) = (true,false,true,true)

scala> ff.tupled(data)
res8: String = true false true true
Assen Kolov
  • 4,143
  • 2
  • 22
  • 32
0
  1. Make a "tupled" function, just like in Assen Kolov's answer:

    def func(d1: Boolean, d2: Boolean, d3: Boolean, d4: Boolean) = ???
    
    val f = func _
    
  2. then create a tuple from your Seq. This answer shows how to do it in a type-safe way.

  3. And call your function f with a tuple argument.

Alexander Azarov
  • 12,971
  • 2
  • 50
  • 54