Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 37 ยท Classes, Traits and Objects

Classes and Constructors

Learn how to define Scala 3 classes: primary and auxiliary constructors, val and var parameters, private members, methods, toString, equality, and creator applications without new.

A class is a blueprint for objects that bundle data with behaviour. Scala classes are much more compact than Java classes because the primary constructor is part of the class header, and its parameters can become fields directly. In this lesson you will define classes, create instances, add methods, use auxiliary constructors and understand how equality and toString work. The Scala code is read-only; runnable Java and Kotlin classes show the equivalent shape.

A first class

SCALA
class Account(val owner: String, var balance: Double):
  def deposit(amount: Double): Unit =
    balance += amount

  def describe: String = s"$owner has $balance"

Use it:

SCALA
val acc = Account("Ada", 100.0)   // no `new` needed in Scala 3
acc.deposit(50)
println(acc.describe)             // Ada has 150.0
println(acc.owner)                // Ada
acc.balance = 10                  // allowed: balance is a var
// acc.owner = "Bob"              // error: owner is a val

Parts of the class:

  • class Account(...) declares the class and its primary constructor in one place.
  • val owner: String creates an immutable public field and a getter-like accessor.
  • var balance: Double creates a mutable public field.
  • The indented body holds methods and extra fields.

Scala 3 makes new optional ("creator applications"): Account("Ada", 100.0) works like new Account(...). Both styles are fine; new is still required in some cases with Java classes.

Kotlin's primary constructor is nearly identical, and you can run it:

Kotlin Class with a primary constructor (Kotlin comparison)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Constructor parameters: val, var or plain

The modifier on a parameter decides what the class stores:

SCALA
class Demo(a: Int, val b: Int, var c: Int, private val d: Int)
Parameter Field? Visible outside? Reassignable?
a (plain) only if used in a method no no
val b yes yes (read) no
var c yes yes (read and write) yes
private val d yes no no

A plain parameter that a method uses becomes a private field automatically. If only the constructor body uses it, no field is created.

SCALA
class Greeter(name: String):
  def hello: String = s"Hello, $name"    // name is captured as a private field

val g = Greeter("Ada")
// g.name                                 // error: name is not a member

Code in the class body

Statements in the class body run as part of the primary constructor each time an instance is created:

SCALA
class Counter(start: Int):
  var count = start
  println(s"Counter created at $start")

  def next(): Int =
    count += 1
    count

Counter(5) prints Counter created at 5. Keep this logic light. Heavy work in a constructor makes classes hard to test.

Default values and named arguments

Constructor parameters can have defaults, and callers can use names:

SCALA
class Server(val host: String = "localhost", val port: Int = 8080)

Server()                      // localhost:8080
Server(port = 9000)           // localhost:9000
Server("example.com", 443)

This usually removes the need for several overloaded constructors.

Validation with require

Check inputs at construction time:

SCALA
class Percent(val value: Int):
  require(value >= 0 && value <= 100, s"out of range: $value")

Percent(150) throws IllegalArgumentException with the message requirement failed: out of range: 150. Use require for caller mistakes and assert for internal assumptions.

The same check in a runnable Java class:

Java Validating in the constructor (Java comparison)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Auxiliary constructors

Extra constructors are methods named this. Each must call another constructor first:

SCALA
class Point(val x: Int, val y: Int):
  def this(x: Int) = this(x, 0)
  def this() = this(0, 0)

Point(3, 4)
Point(3)       // x = 3, y = 0
Point()        // origin

In practice, default parameters or companion apply methods (see singleton objects and companions) are preferred over auxiliary constructors.

Methods and fields

SCALA
class Rectangle(val width: Double, val height: Double):
  val area: Double = width * height          // computed once
  def perimeter: Double = 2 * (width + height) // computed on each call
  def scale(factor: Double): Rectangle =
    Rectangle(width * factor, height * factor)

A val in the body is computed once at construction; a def runs every time. Use lazy val for expensive fields that may never be used. Note that scale returns a new object instead of changing this one: immutable classes like this are easy to reason about.

Methods without parameters can be called without parentheses if declared without them. Declare def perimeter: Double for a getter-like computation and def reset(): Unit for an action.

Printing and equality

By default, printing a plain class shows the class name and a hash:

SCALA
class Dog(val name: String)
println(Dog("Rex"))         // Dog@1b2c3d (varies)
Dog("Rex") == Dog("Rex")    // false: different objects

Override toString, and equals/hashCode if you want value equality:

SCALA
class Dog(val name: String):
  override def toString: String = s"Dog($name)"
  override def equals(other: Any): Boolean = other match
    case d: Dog => d.name == name
    case _ => false
  override def hashCode: Int = name.hashCode

That is a lot of boilerplate, which is why case classes exist. They generate toString, equals, hashCode and copying for you; they are the subject of the next chapter.

this and chaining

this refers to the current instance. Returning this allows chained calls (a "fluent" style):

SCALA
class Builder:
  private val parts = scala.collection.mutable.ListBuffer[String]()
  def add(p: String): this.type =
    parts += p
    this
  def build: String = parts.mkString(" ")

Builder().add("a").add("b").build    // "a b"

Generic classes

Classes can take type parameters in square brackets:

SCALA
class Box[A](val item: A):
  def map[B](f: A => B): Box[B] = Box(f(item))

val b = Box(21).map(_ * 2)     // Box[Int] holding 42

Common mistakes

  • Forgetting val and then wondering why acc.owner does not compile.
  • Doing heavy work in the class body, so every instance creation is slow.
  • Using var fields everywhere. Prefer immutable fields and methods that return new objects.
  • Comparing objects with == and expecting value equality for a plain class.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the val keyword on a constructor parameter do?

    class A(val x: Int) creates a public immutable field x. var would make it mutable.
  2. 2. Where does the primary constructor live in a Scala class?

    The parameter list after the class name defines the primary constructor, and the class body runs as its code.
  3. 3. What is the purpose of require(condition, message)?

    require validates arguments and fails with IllegalArgumentException if the condition does not hold.
  4. 4. What is the effect of def this(x: Int) = this(x, 0) in a class?

    Auxiliary constructors are methods named this that must call another constructor.

Summary

  • The primary constructor is in the class header; val/var parameters become fields.
  • The body runs at construction; keep it light and validate with require.
  • Defaults and named parameters replace most overloaded constructors; auxiliary constructors use def this.
  • Prefer immutable fields and methods that return new instances.
  • Plain classes compare by reference; case classes (later) give value equality for free.

Next: Singleton Objects and Companions