Named Arguments allow you to call a function without passing the arguments in the order as they are defined in the function. In a normal function call, we need to pass the arguments with reference to the function’s parameters.
The following program gives a simple explanation of named arguments:
def house(name: String, rooms: Int): Unit = {println("House "+name+" has "+rooms.toString+" rooms")}house("JacksonVilla", 4)house(name = "JacksonVilla", rooms = 4) //named argumentshouse( rooms = 4, name = "JacksonVilla") //named argumentshouse("JacksonVilla", rooms = 4)
Notice in the above code that we changed the order of parameters in lines 6 and 7 using named arguments. However, when some arguments are named, and others are not, we need to ensure that the unnamed arguments come first and preserve the order of the function’s definition, as shown in line 8.
Free Resources