Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "code: => Unit" mean in scala?

Tags:

Does anyone know the type of => Unit in scala? I don't know the meaning of => Unit and how to use it. I defined a function like below:

def test(code: => Unit){    print("start ...")    code    print("end ....") }  test(print(1)) 

Does it means a function with any arguments returning Unit?

Thanks

like image 890
woods Avatar asked Jun 09 '11 17:06

woods


People also ask

What does => mean in Scala?

=> is the "function arrow". It is used both in function type signatures as well as anonymous function terms. () => Unit is a shorthand for Function0[Unit] , which is the type of functions which take no arguments and return nothing useful (like void in other languages).

What does Unit mean in Scala?

The Unit type in Scala is used as a return statement for a function when no value is to be returned. Unit type can be e compared to void data type of other programming languages like Java. It is a subclass of anytype trait and is used when nothing means to return by the function.

What is some () in Scala?

Scala some class returns some value if the object is not null, it is the child class of option. Basically, the option is a data structure which means it can return some value or None. The option has two cases with it, None and Some. We can use this with the collection.


1 Answers

This kind of parameter are called by-name parameter

=> B represents a block a of code which return a B value, their purpose is that they are evaluated only when you call the parameter.

def foo(code: => Int) {     println("Not yet evaluated")     val result = code     println("parameter evaluated %s, is it an int ? %s " format (            result, result.isInstanceOf[Int]) ) } 

And you can call foo in the following way :

foo(1)  

or

val a = 3 val b = 5 foo {   val c = a * a   c * b } 

The other style of passing parameter is by-value : parameters are evaluated before they are sent to the method

def foo(code : Int) {     println("Parameter already evaluated")     val result = code     println("parameter evaluated : " + result) } 

References

Extract from the Book Functionnal Programming in Scala

More differences between by-name parameter and by-value parameter illustrated

like image 58
Mach Andy Avatar answered Sep 19 '22 07:09

Mach Andy