home search about rss feed twitter ko-fi

Functions: Named Parameters (Scala 3 Video)

When you call a Scala function, you can specify the parameter names when passing in your values. For instance, given this function:

def truncate(string: String, length: Int): String = 
    string.take(length)

you can call it like this:

val a = truncate("freedom", 4)

and you can also call it like this, specifying the parameter names:

val a = truncate(
    string = "freedom",
    length = 4
)

Developers don’t often use this feature, but it can be helpful in situations like this, where all the parameters have the same type:

engage(true, true, true, false)

If you’re not using an IDE, this can be easier to read:

engage(
    speedIsSet = true,
    directionIsSet = true,
    picardSaidMakeItSo = true,
    turnedOffParkingBrake = false
)

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