Scala's Unit roughly corresponds to which Java type?
Get an explanation when it's available:
  • Unit is a subtype of scala.AnyVal. There is only one value of type Unit, (), and it is not represented by any object in the underlying runtime system. A method with return type Unit is analogous to a Java method which is declared void.
  • Unit
    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 quizzes
Sign Up Now
or Subscribe for future quizzes