home search about rss feed twitter ko-fi

Functions: Defaults for Input Parameters (Scala 3 Video)

This is a short lesson that shows that Scala function input parameters can have default values.

Here’s an example, where both timeout and protocol have default values:

class Connection:
    def makeConnection(
        timeout: Int = 5_000,        // default value
        protocol: String = "https"   // default value
    ): Unit =
        println(f"timeout = ${timeout}%d, protocol = ${protocol}%s")
        // more code here

// create a new instance
val c = Connection()

// different ways you can call the function
c.makeConnection()                 // timeout = 5000, protocol = https
c.makeConnection(2_000)            // timeout = 2000, protocol = https
c.makeConnection(3_000, "http")    // timeout = 3000, protocol = http

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