← Back to Scala Course | Chapter 1: Setup & Basics | Lesson 6 of 8

object vs class

A class is a blueprint you can make many copies from, while an object is a single one-of-a-kind thing. It is like a cookie cutter versus one special trophy on the shelf.

In this page:

  1. object vs class
Syntax
scala
class ClassName(param: Type) {
  // instance members
}
val instance = new ClassName(value)

object ObjectName {
  // single instance members
}

object vs class

A class is a blueprint you instantiate with new to create possibly many independent objects, while an object defines a single, lazily-initialized singleton instance directly -- there's only ever one.

Objects are commonly used for utility functions, constants, and program entry points (as seen with object Main). A class and an object with the same name in the same file form a "companion" pair, covered in a later chapter.

Note: Use object for a single shared instance (like utilities or an app's entry point), and class when you need multiple independent instances.

Example: object vs class

markup
class Counter {
  var count = 0
  def increment(): Unit = { count += 1 }
}

object MathUtils {
  def square(n: Int): Int = n * n
}

object Main extends App {
  val c1 = new Counter()
  val c2 = new Counter()
  c1.increment()
  c1.increment()
  c2.increment()

  println(s"c1.count = ${c1.count}, c2.count = ${c2.count}")
  println(s"MathUtils.square(5) = ${MathUtils.square(5)}")
}
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. Trying to create an instance of an object with new MathUtils, when an object is already a single instance.
  2. Calling Counter.increment() on a class name, when the method needs an instance such as new Counter().increment().
  3. Putting utility methods in a class when they do not need state, making you create an instance you do not need; put them in an object.
🔒

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.