Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Problems
  • Python
  • C
  • C++
  • Java
  • Courses
  • Machine Learning
  • DevOps
  • Web Development
  • System Design
  • Aptitude
  • Projects
Open In App
Next Article:
Parameterless Method in Scala
Next article icon

How to define Optional Parameter in Scala?

Last Updated : 01 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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

Scala
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:

  • def <MethodName> (<VariableName/Parameter>: <Datatype> = "<DefaultValue>"): <Return Type> = {// code}
  • def item (sweetitem: String = "Chocolate"): Unit = {//code}

Explanation:

  • Created an object named "OptionalParametersExample1" in which we defined method item and another main method.
  • Defined 'item' method with single parameter 'sweetitem' of String type. It has a default value 'Chocolate'. This function prints a statement like - 'Sweet Chocolate'.
  • 'Unit' is similar to void in other languages which means it doesn't return any value.
  • The another main method serves as an entry point of the program. The program execution starts from here.
  • The item method is called twice, first time when the method was invoked was without providing any arguments i.e. 'item()' and second time the method was invoked by passing an argument i.e. 'item("Ice Cream")'.

Explanation of the Output:

  • The execution starts from the main method.
  • In main method, the 'item()' is invoked which reverts to the functionality of 'item' method. Since, no argument is provided, the method uses the default value set to the parameter. So the output when 'item()' is invoked comes out to be "Sweet Chocolate!".
  • When the 'item' method is invoked with passing argument, the default value is ignored and the argument which is passed becomes the value of the parameter and that will be used in place of the default one. So the output of second line i.e. item("Chocolate") is - "Sweet Ice Cream!".

Output:

Screenshot-2024-03-16-191047
Example1

Lets see more examples for the same.

Example2: Simple Example with multiple Optional Parameter.

Scala
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:

  • def <MethodName> (<Parameter1>: <Datatype > == <DefaultValue1>, <Parameter2>: <Datatype> = <DefaultValue2>){//code}
  • def newname(noun: String = "Panda", adjective: String = "Fluffy"){//code}

Explanation:

  • In above example-Example-2, we defined a method named 'newname' which takes 2 parameters and both the parameters has default values.
  • In main method, we invoked the newname method thrice by passing arguments in different way or number.

Explanation of the Output:

  • First, newname method is invoked with none arguments passed so it used default value set i.e. "Panda" and "Fluffy". So this sets the output to be - "Fluffy Panda!".
  • Now, the second time the method is invoked by passing both the arguments i.e. "Animal" and "Cute". This sets the output to be - "Cute Animal!".
  • And lastly, the method is invoked by passing single argument which is dedicated to "noun". As we haven't passed the second argument, the default argument is used for the adjective parameter and this sets the output to - "Fluffy Bear!".

Output:

Screenshot-2024-03-16-204902
Example2

Example3: Simple Example of Optional Parameters with Different Datatypes.

Scala
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:

  • def marks(name: String = "Mihika", marks: Int = 95){//code}

Explanation:

  • "marks" method is defined having 2 parameters of different datatypes i.e. one is string and another is number/Integer.
  • This method takes two parameters and presents output in form of student and their marks
  • The execution start from the main method.

Explanation of Output:

  • First "marks()" is invoked and as you can see the method i called with no arguments, default values set to the parameters will be used. so the output will be - "Mihika got 95 marks.".
  • Next, the method is called by passing value to the second parameter and no argument or value is passed to the first one. In this case, the first argument will be set to the default value and the second argument or value considered will be the passed one. So the output is - "Mihika got 70 marks.".
  • Next, the method is called by passing both arguments and in such case, no default values are used and priority goes to the arguments passed. The output is set to be - "Nirali got 85 marks.".
  • Next, we can see that only one argument is passed without mentioning to which parameter it is passed to it by default sets that particular argument passed to the first parameter. This means the argument passed is equal to "name" and no second argument is passed so default value set will be used. The output comes out to be - "Sourav got 95 marks.".
  • At the last, the method is invoked by passed both the arguments which means the output turn out to be - "Shravan got 100 marks.".

Output:

Screenshot-2024-03-16-213143
Example3

Next Article
Parameterless Method in Scala

M

mihikaphsj
Improve
Article Tags :
  • Scala

Similar Reads

  • Optional Parameters in LISP
    Optional Parameters are the parameters that are optional in the function. We can put optional parameters whenever the arguments are not necessary. If we keep the optional parameters in a function and pass the values, then the values are taken in place of optional parameters. If values are not passed
    2 min read
  • How to Pass Optional Parameters to a Function in Python
    In Python, functions can have optional parameters by assigning default values to some arguments. This allows users to call the function with or without those parameters, making the function more flexible. When an optional parameter is not provided, Python uses its default value. There are two primar
    5 min read
  • Implicit Parameters In Scala
    Implicit parameters are the parameters that are passed to a function with implicit keyword in Scala, which means the values will be taken from the context in which they are called. In simpler terms, if no value or parameter is passed to a method or function, then the compiler will look for implicit
    2 min read
  • Parameterless Method in Scala
    Prerequisites - Scala | Functions A parameterless method is a function that does not take parameters, defined by the absence of any empty parenthesis. Invocation of a paramaterless function should be done without parenthesis. This enables the change of def to val without any change in the client cod
    2 min read
  • How to resolve type mismatch error in Scala?
    A type mismatch error in Scala is a compile-time error that occurs when the compiler detects an inconsistency between the expected type and the actual type of an expression, variable, or value. There are different methods to resolve type mismatches in Scala. In this article, we are going to discuss
    3 min read
  • How to take Input from a User in Scala?
    This article focuses on discussing various approaches to taking input from a user in Scala. Table of Content Using scala.io.StdIn.readLine() MethodUsing java.util.ScannerUsing Command-line ArgumentUsing scala.io.StdIn.readLine() MethodBelow is the Scala program to take input from the user: [GFGTABS]
    1 min read
  • Scala Int intValue() method with example
    The intValue() method is utilized to return the int value of the specified value. Method Definition: def intValue(): Byte Return Type: It returns the int value of the given value. Example #1: // Scala program of Int intValue // method // Creating object object GfG { // Main method def main(args:Arra
    1 min read
  • Scala | Methods to Call Option
    The Option in Scala is referred to a carrier of single or no element for a stated type. When a method returns a value which can even be null then Option is utilized i.e, the method defined returns an instance of an Option, in place of returning a single object or a null. There are a few methods that
    5 min read
  • How to check String is null in Scala?
    In this article, we will learn how to check if a string is null in Scala. In Scala, you can check if a string is null using the following methods: Table of Content 1. Using the == operator:2. Using the eq method (recommended):3. Using Pattern Matching:1. Using the == operator:[GFGTABS] Scala object
    2 min read
  • How to skip only first element of List in Scala
    In Scala, list is defined under scala.collection.immutable package. A list is a collection of same type elements which contains immutable data. Let's see how to print the element of given List, by skipping the first item in Scala. List in Scala contains many suitable methods to perform simple operat
    1 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences