← Back to Scala Course | Chapter 2: Variables & Types | Lesson 7 of 8

The Unit Type

In this page:

  1. The Unit Type

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

markup
object Main extends App {
  def logMessage(msg: String): Unit = {
    println(s"LOG: $msg")
  }

  val result: Unit = logMessage("started")
  println(result)
}
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.