Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

scala

What are Named Arguments in Scala?

Adnan Abbas

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.

Example

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 arguments 
house( rooms = 4, name = "JacksonVilla") //named arguments
house("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.

RELATED TAGS

scala

CONTRIBUTOR

Adnan Abbas
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring