Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala variable argument list with call-by-name possible?

Tags:

scala

I've got some code like this:

def foo (s: => Any) = println(s)

But when I want to transform this to an argument list with variable length, it won't compile anymore (tested on Scala 2.10.0-RC2):

def foo (s: => Any*) = println(s)

What must I write, that it works like this?

like image 553
Themerius Avatar asked Nov 09 '12 11:11

Themerius


People also ask

What is call by name and call-by-value in Scala?

Call by-name evaluation is similar to call by-value, but it has the advantage that a function argument won't be evaluated until the corresponding value is used inside the function body. Both strategies are reduced to the final value as long as: The reduced expression consists of pure functions.

What are by name parameters in Scala?

By-name parameters are evaluated every time they are used. They won't be evaluated at all if they are unused. This is similar to replacing the by-name parameters with the passed expressions. They are in contrast to by-value parameters. To make a parameter called by-name, simply prepend => to its type.

Does Scala pass by reference?

In Java and Scala, certain builtin (a/k/a primitive) types get passed-by-value (e.g. int or Int) automatically, and every user defined type is passed-by-reference (i.e. must manually copy them to pass only their value).

What is the difference between call-by-value and call by name?

In other words, the call by value function arguments are evaluated once before entering the function, but the call by name function arguments are evaluated inside the function only when they are needed. Hope this helps!


1 Answers

You have to use zero-argument functions instead. If you want, you can

implicit def byname_to_noarg[A](a: => A) = () => a

and then

def foo(s: (() => Any)*) = s.foreach(a => println(a()))

scala> foo("fish", Some(7), {println("This still happens first"); true })
This still happens first
fish
Some(7)
true
like image 181
Rex Kerr Avatar answered Oct 02 '22 15:10

Rex Kerr