Unit Example

Here’s an example:
scala> def doTwoTimes(fn: (Int) => Unit) = {
     |   fn(1); fn(2); 
     | }
doThreeTimes: ((Int) => Unit)Unit
scala> doTwoTimes(println)
scala> def specialPrint(num: Int) = {
     |    println(">>>" + num + "<<<")
     | }
specialPrint: (Int)Unit
scala> doTwoTimes(specialPrint)
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.

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback
Keep exploring
Scala snippets
Sign Up Now
or Subscribe for future quizzes