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.

Follow CodeGalaxy

Mobile Beta

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