Scala – Function parameter with Default Value

In Scala, we have seen how to pass the function as parameter. Now, Suppose you want to define your function in such a way that if you don’t pass any arguments, it gives you a default result instead of throwing any error and you have the choice to pass any parameter or not.

Example:

object FuncWithDefaultParam {
  def main(args: Array[String]): Unit = {

    println("passing 2,3 - Result: "+addition(2,3))  //Calling function with 2 parameters /Result : 2 + 3
    println("Passing 2 - Result: " + addition(2))  //Calling function with 1 parameters /Result : 2 + 0
    println("passing nothing - Result: " +addition())  //Calling function with no parameters /Result : 0 + 0
  }

  def addition(a:Int=0,b:Int=0): Int ={
    a + b
  }
}
Output:
passing 2,3 - Result: 5
Passing 2 - Result: 2
passing nothing - Result: 0
Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...