Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

By-name repeated parameters

How to pass by-name repeated parameters in Scala?

The following code fails to work:

scala> def foo(s: (=> String)*) = {
<console>:1: error: no by-name parameter type allowed here
       def foo(s: (=> String)*) = {
                   ^

Is there any other way I could pass a variable number of by name parameters to the method?

like image 610
Green Hyena Avatar asked Apr 25 '10 04:04

Green Hyena


2 Answers

It works in Scala 3:

scala> def f(i: => Int*): Int = i.sum
def f(i: => Int*): Int

scala> f(1, 2, 3)
val res0: Int = 6
like image 187
Radek Tkaczyk Avatar answered Oct 12 '22 23:10

Radek Tkaczyk


This isn't very pretty but it allows you to pass byname parameters varargs style

def printAndReturn(s: String) = {
  println(s)
  s
}

def foo(s: (Unit => String)*) {
  println("\nIn foo")
  s foreach {_()}  // Or whatever you want ...
}

foo()

foo((Unit) => printAndReturn("f1"),
    (Unit) => printAndReturn("f2"))

This produces

In foo

In foo f1 f2

like image 21
Don Mackenzie Avatar answered Oct 13 '22 00:10

Don Mackenzie