-2

What does the (code: => Unit) parameter do in this scala function from the scala documentation:

def unless(exp: Boolean)(code: => Unit): Unit = if (!exp) code
unless(x < 5) {
  println("x was not less than five")
}

Link

user3685285
  • 6,066
  • 13
  • 54
  • 95
  • 2
    Not a duplicate. How was I supposed to know what this was called in scala...I was asking about it from the syntax point of view. How many other users will have my question and not find the other answer... – user3685285 May 07 '17 at 16:16

1 Answers1

2

The => syntax inside of a function's parameter list means that that parameter is itself a function (known as a higher-order function). What that function signature is saying is that unless is a function that takes a boolean, and take a function that takes no parameters and returns Unit. Here are some more examples:

// This is a function that takes as a parameter that is a function that takes an Int, and returns a Boolean
def foobar(f: Int => Boolean) = ???

// It might be called like this:
foobar(i => i / 2 == 0)

// Which is the same as this
def isEven(i: Int): Boolean = {
  i / 2 == 0
}
foobar(isEven)
Tyler
  • 17,669
  • 10
  • 51
  • 89
  • I get that, but 'code' is a function that takes a 'what' and returns Unit? It would make sense to me if it was (code: Int => Unit) – user3685285 May 09 '17 at 15:04
  • This is incorrect. `code: => Unit` is a by-name parameter, not a function. – puhlen Aug 31 '17 at 19:31