Is there any way to call a Scala function that takes individual parameters, given an array (similar to JavaScript Spreads in ECMAScript 6)?
ys = [10.0, 2.72, -3.14]
f(x, ...ys);
The cleanest syntax would be:
f(1, ys)
but that does not appear to be possible. Even f(1, ys:_*)
does not work (and neither does f(ys:_*)
, as the compiler reports too few parameters - only the first one is filled).
Example:
def f (a:Int, b:Float, c:Float, d:Float): String
val x = 1
val ys = List(10.0, 2.72, -3.14) // note: non-Objects
val result = f(x, ys) // intuitive, but doesn't work
Use Case: injecting test data (from collections) into existing methods that accept individual parameters. As these are test cases, it's quite alright if the #params in ys doesn't match up and that gives either a runtime error or incorrect result.
The question is whether Scala allows a clean syntax for calling a function that takes individual parameters, given a collection of parameters -- not whether it is a good design (although opinions are certainly welcome).
ys
has less than 3 elements or more? – Rupertf
is what comes to mind. That would allow you to call the function in the way you've provided, but it will fail in other situations – Acetylene