What does x: => Int mean in Scala?

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?

1 Like

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

4 Likes

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 ().

3 Likes

Hello,

I think I might have just what you need: https://www.slideshare.net/pjschwarz/non-strict-functions-bottom-and-scala-byname-parameters

2 Likes

this is really good

great to hear that! - I am glad you find it useful - thanks for the feedback

1 Like

Video 9 in this playlist covers pass-by-name.

1 Like

maybe think of it as a "def’ instead of a “val” being passed in.

3 Likes

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.

2 Likes