Scala variable argument list with callability by name?

I have code like this:

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

But when I want to convert this to a variable-length argument list, it will no longer compile (tested on Scala 2.10.0-RC2):

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

What should I write for it to work like this?

+7
source share
2 answers

Instead, you need to use functions with a null argument. 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 
+10
source

There is a problem: https://issues.scala-lang.org/browse/SI-5787

For the accepted answer, to restore the desired behavior:

 object Test { import scala.language.implicitConversions implicit def byname_to_noarg[A](a: => A) = () => a implicit class CBN[A](block: => A) { def cbn: A = block } //def foo(s: (() => Any)*) = s.foreach(a => println(a())) def foo(s: (() => Any)*) = println(s(1)()) def goo(a: =>Any, b: =>Any, c: =>Any) = println(b) def main(args: Array[String]) { foo("fish", Some(7), {println("This still happens first"); true }) goo("fish", Some(7), {println("This used to happens first"); true }) foo("fish", Some(7), {println("This used to happens first"); true }.cbn) } } 

Sorry grammar lolcats.

+5
source

All Articles