9

我有一些这样的代码:

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

但是当我想将其转换为具有可变长度的参数列表时,它将不再编译(在 Scala 2.10.0-RC2 上测试):

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

我必须写什么,它是这样工作的?

4

2 回答 2

11

您必须改用零参数函数。如果你愿意,你可以

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

接着

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
于 2012-11-09T12:23:59.527 回答
6

有一个问题: https ://issues.scala-lang.org/browse/SI-5787

对于接受的答案,要恢复所需的行为:

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)
  }
}

原谅lolcats语法。

于 2012-11-10T01:00:02.940 回答