Default And Named Arguments (Scala)

Reading Time: 2 minutes
Scala

Overview

In this blog, we are going to discuss the support of default and named arguments in SCALA.

The method that takes multiple parameters of the same types is subject to mistakes that are invisible during compile time exchanging two arguments of the same type does not result in an error, but it can produce an unexpected outcome.

Adding named parameters can simply solve this problem. Additionally named arguments to make a method call with a large number of arguments easier to interpret.

Default Arguments

The form of a method parameter with a default argument is “p:T= expression,” where expression is evaluated every time of default argument is used by a method application.

To use the default arguments, the relevant parameters in the method application must be omitted.

def defaultArgs[A](input: Array[A], 
                   beginning: String ="(",
                   segregate: String= ",",
                   ending: String=")"): String = 
input.mkstring(beginning , segregate, ending)

defaultArgs generates a nice String representation of a generic array. The input array, its first argument, has no default values, whereas all of the other parameters do.

As a result, we have two options for calling defaultArgs. Just because we are satisfied with the method definition’s default parameters, we can omit all but the first argument:

defaultArgs(Array(1, 2, 3)) shouldBe "(1,2,3)"

At the same time, there is no loss of flexibility. Let us take an example, if we want the elements of an input array to be wrapped in square brackets and separated by semicolons, we can use prettyPrint with the following arguments:

defaultArgs(Array(1, 2, 3), "[", ";", "]") shouldBe "[1;2;3]"

Named Arguments

Scala allows us to label method parameters with their names, which improves readability and makes code less error-prone in many cases.

namedArgs(Array(1, 2, 3, 4, 5), start = "[", separator = ";", end = "]") shouldBe "[1;2;3;4;5]"

When using named arguments, the only rule to remember is that unnamed parameters must always come before named ones. If we make an error here, the code will fail to compile:

namedArgs(start = "{", separator = ",", end = "}", Array(1, 2, 3))

Conclusion

In this tutorial, we learned how named and default arguments support in Scala can improve the readability of our code by making it less verbose.

for more updates please visit https://blog.knoldus.com/

Reference

https://www.baeldung.com/scala/named-default-arguments

knoldus

Leave a Reply