Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to write a repeated-parameter function through function literal in scala ?

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 .

like image 774
爱国者 Avatar asked Dec 20 '22 18:12

爱国者


2 Answers

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 _
like image 53
Jörg W Mittag Avatar answered May 16 '23 08:05

Jörg W Mittag


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)
like image 39
Jan Avatar answered May 16 '23 08:05

Jan