Function parameters with and without () in Scala

I play with code examples related to Scala in the action book http://www.manning.com/raychaudhuri/

Quote from https://github.com/nraychaudhuri/scalainaction/blob/master/chap01/LoopTill.scala

// Run with >scala LoopTill.scala or // run with the REPL in chap01/ via // scala> :load LoopTill.scala object LoopTillExample extends App { def loopTill(cond: => Boolean)(body: => Unit): Unit = { if (cond) { body loopTill(cond)(body) } } var i = 10 loopTill (i > 0) { println(i) i -= 1 } } 

In the above code cond: => Boolean there is a place where I got confused. When I changed it to cond:() => Boolean , it failed.

Can someone explain to me what distinguishes

 cond: => Boolean 

and

 cond:() => Boolean 

Don't they both represent params for a function?

+6
source share
1 answer

I am by no means a scala expert, so take my answer with lots of salt.

The first, cond: => Boolean , is a by-name parameter. To keep things simple, this is essentially the syntactic sugar for the arity 0 function - it is a function, but you are treating it as a variable.

The second, cond: () => Boolean , is an explicit parameter of the function - when you refer to it without adding parameters, you do not actually call the function, you refer to it. In your code, if(cond) cannot work: the function cannot be used as a boolean. Of course, this return value may be due to the fact that you need to explicitly evaluate it ( if(cond()) ).

There is a lot of documentation on name-by-name parameters, a very powerful function in Scala, but as I understand it, it can simply be regarded as syntactic sugar.

+7
source

Source: https://habr.com/ru/post/953135/


All Articles