Tuesday 1 September 2020

Scala: Default values to arguments

You can specify a default value to a function parameter in Scala. When the user do not specify any value to the parameter, the default one takes place.


Example

def welcomeUser(message : String = "Hello", name : String = "user") : Unit = {
     println(message + " " + name)
}

‘welcomeUser’ function is defined with two arguments, where the first parameter ‘message’ has the default value "Hello" and the second parameter ‘name’ has the default value "user".

 

welcomeUser()

When you call ‘welcomeUser()’ function without any arguments message ‘Hello user’ gets printed to the console.

 

welcomeUser("Good Morning")

In this case, message is assigned with value "Good Morning" and the default value considered for the parameter ‘name’.

 

welcomeUser(name = "Ram")

In this case, name is assigned with value "Ram" and the default value considered for the parameter ‘message’. You can use named and default parameters together.

 

welcomeUser("Good Morning", "Ram")

In this case, message is assigned with value "Good Morning", name is assigned with value "Ram".

scala> def welcomeUser(message : String = "Hello", name : String = "user") : Unit = {
     |    println(message + " " + name)
     | }
def welcomeUser(message: String, name: String): Unit

scala> 

scala> welcomeUser()
Hello user

scala> welcomeUser("Good Morning")
Good Morning user

scala> welcomeUser("Good Morning", "Ram")
Good Morning Ram

scala> welcomeUser(name = "Ram")
Hello Ram






Previous                                                    Next                                                    Home

No comments:

Post a Comment