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

object vs class

In this page:

  1. object vs class

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)}")
}
🔒

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.