简体   繁体   English

Scala变量参数列表可能带有call-by-name吗?

[英]Scala variable argument list with call-by-name possible?

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

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

What must I write, that it works like this? 我必须写什么,它是这样的?

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

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

For the accepted answer, to recover 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)
  }
}

Excuse the lolcats grammar. 请原谅lolcats语法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM