‹ BACK

Unit Example

Unit
Here’s an example:
scala> def doTwoTimes(fn: (Int) => Unit) = {
     |   fn(1); fn(2); 
     | }
doThreeTimes: ((Int) => Unit)Unit
 
scala> doTwoTimes(println)
1
2
 
scala> def specialPrint(num: Int) = {
     |    println(">>>" + num + "<<<")
     | }
specialPrint: (Int)Unit
 
scala> doTwoTimes(specialPrint)
>>>1<<<
>>>2<<<
>>>3<<<
In the definition of doTwoTimes we specify that the method takes a parameter called fn, which has a type of (Int) => Unit. This means that fn is a method that takes a single parameter of type Int and a return type of Unit, which is to say fn isn’t supposed to return a value at all just like a Java void function.
unit void return type

To check your knowledge the following tests are recommended:
Check your scala scala skills.