Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function literal with call-by-name parameter

Tags:

scala

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?

like image 598
Sjlver Avatar asked Mar 01 '13 23:03

Sjlver


1 Answers

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
like image 57
Daniel C. Sobral Avatar answered Sep 27 '22 02:09

Daniel C. Sobral