home search about rss feed twitter ko-fi

Classes: Auxiliary Constructors (and Default Parameter Values) (Scala 3 Video)

To create auxiliary class constructors, create this methods inside the class. Each constructor must take a different set of constructor parameters.

Auxiliary constructors

An example class with three auxiliary constructors:

class Pizza:

    var crustSize = Medium
    var crustType = Regular

    def this(cs: CrustSize, ct: CrustType) = 
        this()
        this.crustSize = cs
        this.crustType = ct

    def this(crustSize: CrustSize) = 
        this()
        this.crustSize = crustSize

    def this(crustType: CrustType) =
        this()
        this.crustType = crustType

    override def toString = 
        s"A $crustSize pizza with a $crustType crust."

end Pizza

These examples show how to use those constructors:

val p1 = Pizza()
val p2 = Pizza(Large, Thin)
val p3 = Pizza(crustSize = Large)
val p4 = Pizza(crustType = Thin)

Constructor parameters with default values

Constructor parameters can also have default values. Just add the default value after the data type, as shown here:

class Socket(val timeout: Int = 10_000):
    override def toString = s"timeout: $timeout, linger: $linger"

This is roughly the equivalent of having multiple constructors:

val s = Socket()
val s = Socket(5_000)

Here's another example with multiple constructor parameters that have different values:

class Socket(val timeout: Int = 10_000, val linger: Int = 5_000):
    override def toString = s"timeout: $timeout, linger: $linger"

This example is the equivalent of having three class constructors:

val s = Socket()
val s = Socket(3000)
val s = Socket(3_000, 4_000)

Note that by specifying the constructor parameter names, you can also create new Socket values like this:

val s = Socket(timeout=3000, linger=4000))
val s = Socket(linger=4000, timeout=3000)
val s = Socket(timeout=3000)
val s = Socket(linger=4000)

Similarly, this class definition:

class Pizza(
    var crustSize: CrustSize = Medium,
    var crustType: CrustType = Regular
):
    override def toString = 
        s"A $crustSize pizza with a $crustType crust."

lets you create a Pizza in these different ways:

val p1 = Pizza()    
val p2 = Pizza(Large, Thin)
val p3 = Pizza(crustSize = Large)
val p4 = Pizza(crustType = Thin)

Update: All of my new videos are now on
LearnScala.dev