Sjlver
Sjlver

Reputation: 1295

Function literal with call-by-name parameter

How does one define an anonymous function with call-by-name parameters in scala?

I tried the following:

val fun = (x: Boolean, y: =>Int) => if(x) y else 0

This works well with call-by-value y, but not with call-by-name. Why?

Upvotes: 10

Views: 1311

Answers (1)

Daniel C. Sobral
Daniel C. Sobral

Reputation: 297265

It can be done, but in a slightly different way: declare the type separately from the parameters:

val fun: (Boolean, => Int) => Int = (x, y) => if (x) y else 0

Upvotes: 19

Related Questions