: => A 语法在方法参数声明中是什么意思?

What does : => A syntax mean in method parameter declaration?

因此,在阅读 Scala 中的 Scala tour about implicit 类 时,我遇到了这段代码:

object Helpers {
  implicit class IntWithTimes(x: Int) {
    def times[A](f: => A): Unit = {
      def loop(current: Int): Unit =
        if(current > 0) {
          f
          loop(current - 1)
        }
      loop(x)
    }
  }
}

让我困扰的是 def times[A](f: => A): Unit = { 行。这里发生了什么? 函数类型参数部分,A,我明白了,但我不能完全理解(f: => A)部分是什么。 它是否表示 f 是一个函数,可以接受任何种类/数量的参数,并且 return 是 A 类型的对象?

因此,这个构造是否有效地意味着一个函数可以接受任何参数并且 return 我想要什么?

这是来自 Scala gitter channel 的关于主题的聊天,为 by-name parameters

提供了一个很好的类比

Gavin Bisesi @Daenyth Feb 24 17:08

=> X is "by-name" syntax It's syntax sugar for something that's very much like () => X The caller doesn't need to supply the () => part, and referencing it in the method body also doesn't need () but otherwise is basically the same

Rob Norris @tpolecat Feb 24 17:17

...I think it's best to think of by-name arguments acting like defs and normal arguments acting like vals. Under the covers it's a nullary function but from the language's point of view it's different. def foo(a: => String) and def foo(a: () => String) have different types and a behaves differently in the body of each foo.

Fabio Labella @SystemFw Feb 24 20:19

@Daenyth re def/val :A /: => A I actually start my tutorials on programs as values with that. def/: => A is related to "being", vs val/: A is related to "doing", and understanding the doing/being dichotomy is really useful to understanding FP with effects, and it also translates to pure FP paradigms that actually use native "doing" (unlike as what we do with programs as values, where everything is "being" and "doing" happens in a metalanguage of combinators such as flatMap). An example would be algebraic effects in Unison