Ad space (banner)
Lesson 17 / 20

object (singletons)

This lesson covers the singleton mechanism behind Scala's object keyword.

Anything defined with object becomes a special instance of which exactly one exists in the program. The object Main extends App used throughout these lessons is in fact this same mechanism.

The sample code defines a singleton, object MathUtils, gathering shared calculations, and calls its methods directly — as in MathUtils.square(5) — without creating an instance.

A common early stumble is choosing between class and object. Remember it as: a class when you need several instances, an object when you only want to gather shared utility functions or constants.

In professional work, an object is the usual home for the kind of logic that would be a static method in Java.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Scala directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)