What does “code: => Unit” mean in scala?

Spread the love

Question Description

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

Practice As Follows

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

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.