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:
Syntax
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
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
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
- Assigning the result of a
Unitmethod to a variable and expecting a value, when it holds(). - Forgetting the
=indef logMessage(msg: String) { ... }style or expecting a return value from a body that ends inprintln. - Writing
returnin aUnitmethod 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: