object vs class
In this page:
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
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)}")
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: