Scala variable argument list with call-by-name possible?

前端 未结 2 760
春和景丽
春和景丽 2020-12-03 12:38

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 leng

相关标签:
2条回答
  • 2020-12-03 12:48

    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
    
    0 讨论(0)
  • 2020-12-03 13:02

    There is an issue: 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.

    0 讨论(0)
提交回复
热议问题