我有一些这样的代码:
def foo (s: => Any) = println(s)
但是当我想将它转换为具有可变长度的参数列表时,它将不再编译(在Scala 2.10.0-RC2上测试):
def foo (s: => Any*) = println(s)
我必须写什么,它是这样的?
答案 0 :(得分: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
答案 1 :(得分: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语法。