devj
devj

Reputation: 1153

Scala , what does this function definition means?

In the following code snippet, what does (F: => T) mean?

def func1[T](arg1: Int, arg2: String)(F: => T): func2[T]

Thanks

Upvotes: 0

Views: 63

Answers (1)

Alexey Romanov
Alexey Romanov

Reputation: 170713

F is the argument name; => T means it's a by-name parameter. It's basically equivalent to () => T with some syntactic sugar:

  1. When invoking this method, the argument will have type T and will automatically be turned into () => T:

    func1[String](0, x)(x + x) ===> func1[String](0, x)(() => x + x)
    
  2. When implementing this method, each use of F turns into F(). So the value of type T will be recalculated each time.

Obviously, this is useful in one of two cases:

  1. if F may not be needed;

  2. if the value returned by F may change between different invocations.

Upvotes: 2

Related Questions