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
=> 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).
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.
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.
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) }
Extract from the Book Functionnal Programming in Scala
More differences between by-name parameter and by-value parameter illustrated
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With