I have come across many functions with parameter type matching x: => T
. For example
def foo(x: => Int) = ()
What does part => Int
in the above line mean?
I have come across many functions with parameter type matching x: => T
. For example
def foo(x: => Int) = ()
What does part => Int
in the above line mean?
This is called call-by-name. It means when you call the method, the argument is not evaluated before the method is executed, but rather, it is evaluated each time it is referred to inside the method.
For example:
> def foo(x: => Int) = { println("Start of method"); println(x); println(x); println("End of method") }
foo: (x: => Int)Unit
> def bar: Int = { println("Evaluating!"); 42 }
bar: Int
> foo(bar)
Start of method
Evaluating!
42
Evaluating!
42
End of method
That’s call by name: https://www.scala-lang.org/files/archive/spec/2.13/04-basic-declarations-and-definitions.html#by-name-parameters
It works like parameterless function () => T
but you don’t need to write the ()
.
Hello,
I think I might have just what you need: https://www.slideshare.net/pjschwarz/non-strict-functions-bottom-and-scala-byname-parameters
this is really good
great to hear that! - I am glad you find it useful - thanks for the feedback
Video 9 in this playlist covers pass-by-name.
maybe think of it as a "def’ instead of a “val” being passed in.
Agree, I think val
and def
is the best way to think about a: A
and a: => A
. I wrote a blog post on this a while back, which OP may or may not find helpful.