Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function parameters with and without () in Scala

Tags:

scala

I am playing around with code examples related to Scala in Action book http://www.manning.com/raychaudhuri/

Quoting 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 above code cond: => Boolean is where I am confused. When I changed it to cond:() => Boolean it failed.

Could someone explain me what is the different between

cond: => Boolean 

and

cond:() => Boolean 

Aren't they both represent params for function ?

like image 336
nish1013 Avatar asked Sep 04 '13 08:09

nish1013


People also ask

What is a function without parameters?

If no parameters are given, then the function does not take any and should be defined with an empty set of parenthesis or with the keyword void.

What kind of parameters are not needed while calling a method in Scala?

A parameterless method is a function that does not take parameters, defined by the absence of any empty parenthesis. Invocation of a paramaterless function should be done without parenthesis.

What happens if you call a function without parameters?

javascript will set any missing parameters to the value undefined . This works for any number of parameters.


1 Answers

I'm by no means a scala expert, so take my answer with a heavy grain of salt.

The first one, cond: => Boolean, is a by-name parameter. To keep things simple, it's essentially syntactic sugar for a function of arity 0 - it's a function, but you handle it as a variable.

The second one, cond: () => Boolean, is an explicit function parameter - when you reference it without adding parameters, you're not actually calling the function, you're referencing it. In your code, if(cond) can't work: a function cannot be used as a boolean. It's return value can be, of course, which is why you need to explicitely evaluate it (if(cond())).

There's a wealth of documentation about by-name parameters, a very powerful feature in Scala, but as far as I understand it, it can just be considered syntactic sugar.

like image 134
Nicolas Rinaudo Avatar answered Oct 19 '22 05:10

Nicolas Rinaudo