BudiBadu Logo
Samplebadu

Scala by Example: Classes

Scala 3

Defining object blueprints with this sample code demonstrating primary constructor parameters in class signature, val for immutable and var for mutable properties, method definitions, auxiliary constructors, and mandatory override keyword for parent method overriding.

Code

// Primary constructor is in the class signature
class User(val name: String, var age: Int) {
  
  // Method definition
  def greet(): Unit = {
    println(s"Hi, I'm $name and I'm $age years old.")
  }
  
  // Auxiliary constructor
  def this(name: String) = this(name, 18)
  
  // Overriding toString
  override def toString: String = s"User($name, $age)"
}

// Creating instances (new keyword optional in Scala 3)
val u1 = new User("Alice", 25)
val u2 = User("Bob") // Uses auxiliary constructor

u1.greet()
u1.age = 26 // Allowed because age is a var

Explanation

In Scala, the primary constructor is uniquely defined directly in the class signature rather than in a separate constructor block. Parameters defined with val become immutable public properties, while those with var become mutable public properties. Parameters without val or var are private to the constructor and don't generate fields. The entire class body serves as the primary constructor, so any code not inside a method executes during object initialization.

Auxiliary constructors provide alternative ways to instantiate a class and are defined using def this(...). Every auxiliary constructor must eventually call either the primary constructor or another auxiliary constructor as its first action using this(...). This ensures that the primary constructor always runs, maintaining consistent initialization. Methods are defined using def just like standalone functions but reside within the class scope.

Scala 3 introduced the ability to instantiate classes without the new keyword, making syntax cleaner and more consistent with case classes. The override keyword is mandatory when overriding a method from a parent class or trait, preventing accidental overrides and making the code's intent explicit. This compile-time check helps catch errors where you think you're overriding a method but have actually created a new one due to a typo or signature mismatch.

Code Breakdown

2
class User(...) defines the class and its primary constructor simultaneously.
10
def this(name: String) creates auxiliary constructor calling primary constructor.
13
override is required to prevent accidental method shadowing.
18
Scala 3 allows instantiation without new keyword for cleaner syntax.