As we know that we can define a repeated-parameter (varargs) function in scala, like this:
def func(s: String*) = println(s)
My question is how to rewrite the above in function literal style. Or is it impossible to do that?
Note: (s: String) => println(s)
is not correct .
As we know that we can define a multi-parameter function in scala, like this:
def func(s: String*) = println(s)
Actually, that's not a function, that's a method. The two are fundamentally different in Scala.
My question is how to rewrite the above in function literal style. Or is it impossible to do that ?
Note:
(s: String*) => println(s)
is not correct.
You cannot define a varargs argument in a function literal. There's a bug report about this in the Scala bug tracker and a comment by Martin Odersky himself that basically says that this would be much too complicated.
There are several ways to cheat, however.
If you use type inference for the function arguments, i.e. if you use the function literal in a context where the argument is statically known to be a varargs argument, then everything works fine:
val func: (String*) => Unit = s => println(s)
Alternatively, you can define a method and then convert it to a partially applied function via η-expansion:
def meth(s: String*) = println(s)
val func = meth _
As written in the comment. You can cheat by first defining a method and then use a function that 'points' to the method:
> def m(str:String*) = println(str)
m: (str: String*)Unit
> val f = m _
f: String* => Unit = <function1>
> f("1", "2")
WrappedArray(1, 2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With