Open In App

How to define Optional Parameter in Scala?

Optional parameters in Scala provide us with a procedure or a way to define some default values for function parameters. The need to define default values comes when a value is not provided for the parameter during function invocation. These are also useful when we want to provide some default or specific values for function parameters. We can control the behavior to an extent using Optional Parameters.

Here is a simple example showing optional parameters.

Example1: Simple Example with a single Optional parameter

object OptionalParametersExample1{
  
 def item(sweetitem: String = "Chocolate"): Unit = {//Optional parameter
     println("Sweet $sweetitem!")//print value either default or custom parameter
 }
    def main(args: Array[String]) {
      //Calling item() with default parameter
      item()//Output: Sweet Chocolate!
      
      //Calling item() with custom parameter
      item("Ice Cream")//Output: Sweet Ice Cream!
    }
}

Definition:

Explanation:

Explanation of the Output:

Output:

Screenshot-2024-03-16-191047

Example1

Lets see more examples for the same.

Example2: Simple Example with multiple Optional Parameter.

object OptionalParameterExample2{
  def newname(noun: String = "Panda", adjective: String = "Fluffy"): Unit{
      println("$adjective $noun")
  }
  def main(args: Array [String]): Unit {
      //Calling item() with no arguments
    newname()//Output: Fluffy Panda!
    
    //Calling newname() by passing 2 arguments
    newname("Animal","Cute")//Output: Cute Animal!
    
    //Calling newname() with 1 argument
    newname("Bear")//Output: Fluffy Bear!
  }
}

Definition:

Explanation:

Explanation of the Output:

Output:

Screenshot-2024-03-16-204902

Example2

Example3: Simple Example of Optional Parameters with Different Datatypes.

object OptionalParametersExample3{
  def marks(name: String = "Mihika", mark: Int = 95): Unit {
      println("$name got $mark marks.")
  }
  def main(args: Array[String]){
    
      marks()//Output: Mihika got 95 marks.
    marks(mark = 70)//Output: Mihika got 70 marks.
    marks("Nirali", 85)//Output: Nirali got 85 marks.
    marks("Sourav")//Output: Sourav got 95 marks.
    marks("Shravan", 100)//Output: Shravan got 100 marks.
    
  }
}

Definition:

Explanation:

Explanation of Output:

Output:

Screenshot-2024-03-16-213143

Example3

Article Tags :