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

The Unit Type

Unit means 'nothing useful to give back', like a helper who does a chore but hands you no object afterwards. It is what functions that only do things, such as printing, produce.

In this page:

  1. The Unit Type
Syntax
scala
def method_name(param: Type): Unit = {
  // side effect only
}

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)
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Assigning the result of a Unit method to a variable and expecting a value, when it holds ().
  2. Forgetting the = in def logMessage(msg: String) { ... } style or expecting a return value from a body that ends in println.
  3. Writing return in a Unit method to give a value back, which does not return anything useful.
🔒

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.