The Unit Type
In this page:
The Unit Type
Unit is Scala's equivalent of void -- it's the type of an expression that produces no meaningful value, like a println call or a loop. Every method that doesn't explicitly return something has an inferred return type of Unit. Unlike void in some languages, Unit is a real type with exactly one value, written ().
Note: A method whose body is { ... } with no final expression value, or ends with a side-effecting call, has its return type inferred as Unit.
Example: The Unit Type
object Main extends App {
def logMessage(msg: String): Unit = {
println(s"LOG: $msg")
}
val result: Unit = logMessage("started")
println(result)
}
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: