dragon
dragon

Reputation: 49

Need help understanding the syntax

I am Scala beginner.I know the syntax for function declaration

def function_name(parameter:return_type):return_type = {function_body} 

Refering this link https://livebook.manning.com/#!/book/scala-in-action/chapter-2/161. I can't get over the code written there

def breakable(op: => Unit) { ... }

Can anyone explain this?

Upvotes: 1

Views: 77

Answers (2)

prayagupadhyay
prayagupadhyay

Reputation: 31192

In scala function can take values(pre-computed values or not-yet-computed values) along with function as arguments.

So, function which takes computed values as argument,

scala> def f(a: Int) = a * 100
f: (a: Int)Int

Example of function which takes a block of code returning Int (not yet computed) , block of code here could be just anonymous or existing method(not a function; that's where things get messy)

scala> def f(a: => Int) = a
f: (a: => Int)Int

and to use it,

scala> def a: Int = 100 * 100
a: Int

scala> f(a) //a returns Int so confirms a: => Int
res3: Int = 10000

In your example, def breakable(op: => Unit) { ... } takes a argument which WILLL be computed as Unit.

For example, you can pass println, which returns Unit,

scala> def breakable(op: => Unit) = op
breakable: (op: => Unit)Unit

scala> breakable { println("i m learning fp") }
i m learning fp

The other thing you will see is function taking function as argument, as in Functor, Monad etc.

For example, map/ flatMap on List[Int] would be

final override def map[B](f: A => B): List[B]
final override def flatMap[B](f: Int => scala.collection.IterableOnce[B]): List[B]

Upvotes: 1

Tim
Tim

Reputation: 27356

This is a shorthand syntax for declaring a function that returns Unit (roughly the same as void in C-like languages).

The definition

def breakable(op: => Unit) { ... }

is the same as

def breakable(op: => Unit): Unit = { ... }

This syntax may be removed in later versions of Scala, so best to include the = even when declaring a function that returns Unit.


The parameter is declared as op: => Unit which means it is a call-by-name parameter. This means that the expression that is passed to this parameter is only evaluated when it is used, and is evaluated every time it is used. In this case it means that you can pass a block of code to breakable in a convenient way:

breakable {
    println("I have been called")
}

Each time breakable evaluates op, the println statement will be executed.

Upvotes: 3

Related Questions