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:
Syntax
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
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
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
- Trying to create an instance of an
objectwithnew MathUtils, when an object is already a single instance. - Calling
Counter.increment()on a class name, when the method needs an instance such asnew Counter().increment(). - Putting utility methods in a
classwhen they do not need state, making you create an instance you do not need; put them in anobject.
🔒
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: