Open In App

Scala | Nested Functions

Last Updated : 06 Jun, 2021
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A function definition inside an another function is known as Nested Function. It is not supported by C++, Java, etc. In other languages, we can call a function inside a function, but it’s not a nested function. In Scala, we can define functions inside a function and functions defined inside other functions are called nested or local functions
Syntax: 
 

def FunctionName1( parameter1, parameter2, ..) = { 
def FunctionName2() = { 
// code 

}

 
Single Nested Function 
Here is an example of single nested function that takes two numbers as parameters and returns the Maximum and Minimum of them. 
Example 
 

Scala




// Scala program of Single Nested Function
object MaxAndMin
{
    // Main method
    def main(args: Array[String])
    {
        println("Min and Max from 5, 7")
                maxAndMin(5, 7);
    }
     
    // Function
    def maxAndMin(a: Int, b: Int) = {
     
       // Nested Function
       def maxValue() = {
          if(a > b)
          {
              println("Max is: " + a)
          }
          else
          {
              println("Max is: " + b)
          }
       }
     
       // Nested Function
       def minValue() = {
          if (a < b)
          {
              println("Min is: " + a)
          }
          else
          {
              println("Min is: " + b)
          }
       }
       maxValue();
       minValue();
    }
}


Output 
 

Min and Max from 5, 7
Max is: 7
Min is: 5

In above code maxAndMin is a function and maxValue is another inner function returns maximum value between a and b similarly minValue is another inner function which is also nested function this function returns minimum value between a and b. 
Multiple Nested Function 
Here is an implementation of multiple nested function. 
Example 
 

Scala




// Scala program of Multiple Nested Function
object MaxAndMin
{
    // Main method
    def main(args: Array[String])
    {
        fun();
    }
     
    // Function
    def fun() = {
         
        geeks();
         
        // First Nested Function
        def geeks() = {
            println("geeks");
             
            gfg();
             
            // Second Nested Function
            def gfg() = {
                println("gfg");
 
                geeksforgeeks();
 
                // Third Nested Function
                def geeksforgeeks() = {
                    println("geeksforgeeks");
                }
            }
        }
    }
}


Output 
 

geeks
gfg
geeksforgeeks

In above code fun is a function and geeks, gfg, geeksforgeeks are nested functions or local function .
 



Similar Reads

Scala | Decision Making (if, if-else, Nested if-else, if-else if)
Decision making in programming is similar to decision making in real life. In decision making, a piece of code is executed when the given condition is fulfilled. Sometimes these are also termed as the Control flow statements. Scala uses control statements to control the flow of execution of the program based on certain conditions. These are used to
5 min read
Scala | Loops(while, do..while, for, nested loops)
Looping in programming languages is a feature which facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true. Loops make the programmers task simpler. Scala provides the different types of loop to handle the condition based situation in the program. The loops in Scala are : while Loopdo..while L
5 min read
How to parse nested JSON using Scala Spark?
In this article, we will learn how to parse nested JSON using Scala Spark. To parse nested JSON using Scala Spark, you can follow these steps:Define the schema for your JSON data.Read the JSON data into a Datc aFrame.Select and manipulate the DataFrame columns to work with the nested structure.Scala Spark Program to parse nested JSON: [GFGTABS] Sca
1 min read
Scala | Partially Applied functions
The Partially applied functions are the functions which are not applied on all the arguments defined by the stated function i.e, while invoking a function, we can supply some of the arguments and the left arguments are supplied when required. we call a function we can pass less arguments in it and when we pass less arguments it does not throw an ex
3 min read
Scala | Functions Call-by-Name
In Scala when arguments pass through call-by-value function it compute the passed-in expression's or arguments value once before calling the function . But a call-by-Name function in Scala calls the expression and recompute the passed-in expression's value every time it get accessed inside the function. Here example are shown with difference and sy
3 min read
Using anonymous functions with the map method in Scala
In Scala, you can use anonymous functions with map method. And here we will discuss the usage of multiple line anonymous functions with map. Therefore, whenever you see that your algorithm is becoming lengthy then instead of utilizing an anonymous function you can firstly define the method and then you can pass it into the map or use it with the ma
2 min read
Scala | Functions - Basics
A function is a collection of statements that perform a certain task. One can divide up the code into separate functions, keeping in mind that each function must perform a specific task. Functions are used to put some common and repeated task into a single function, so instead of writing the same code again and again for different inputs, we can si
3 min read
Currying Functions in Scala with Examples
Currying in Scala is simply a technique or a process of transforming a function. This function takes multiple arguments into a function that takes single argument. It is applied widely in multiple functional languages. Syntax def function name(argument1, argument2) = operation Let's understand with a simple example, Example: // Scala program add tw
3 min read
Partial Functions in Scala
Introduction: When a function is not able to produce a return for every single variable input data given to it then that function is termed as Partial function. It can determine an output for a subset of some practicable inputs only. It can only be applied partially to the stated inputs. Some important points: Partial functions are beneficent in un
4 min read
Higher Order Functions in Scala
A function is called Higher Order Function if it contains other functions as a parameter or returns a function as an output i.e, the functions that operate with another functions are known as Higher order Functions. It is worth knowing that this higher order function is applicable for functions and methods as well that takes functions as parameter
3 min read
Anonymous Functions in Scala
In Scala, An anonymous function is also known as a function literal. A function which does not contain a name is known as an anonymous function. An anonymous function provides a lightweight function definition. It is useful when we want to create an inline function. Syntax: (z:Int, y:Int)=&gt; z*yOr(_:Int)*(_:Int)In the above first syntax, =&gt; is
2 min read
Scala short &lt;(x: Short): Boolean
Short, a 16-bit signed integer (equivalent to Java's short primitive type) is a subtype of scala.AnyVal. The &lt;(x: Short) method is utilized to return true if this value is less than x, false otherwise. Method Definition: def &lt;(x: Short): Boolean Return Type: It returns true if this value is less than x, otherwise false. Example #1: // Scala p
1 min read
Scala short &lt;(x: Char): Boolean
Short, a 16-bit signed integer (equivalent to Java's short primitive type) is a subtype of scala.AnyVal. The &lt;(x: Char) method is utilized to return true if this value is less than x, false otherwise. Method Definition: def &lt;(x: Char): BooleanReturn Type: It returns true if this value is less than x, otherwise false. Example #1: C/C++ Code //
1 min read
Scala Extractors
In Scala Extractor is defined as an object which has a method named unapply as one of its part. This method extracts an object and returns back the attributes. This method is also used in Pattern matching and Partial functions. Extractors also explains apply method, which takes the arguments and constructs an object so, it's helpful in constructing
6 min read
Scala String indexOf(String str) method with example
The indexOf(String str) method is utilized to return the index of the sub-string which occurs first in the string stated. Method Definition: indexOf(String str) Return Type: It returns the index of the sub-string which is specified in the argument of the method. Example #1: // Scala program of int indexOf() // method // Creating object object GfG {
1 min read
Scala String contentEquals() method with example
The contentEquals() method is utilized to compare a string to the content of StringBuffer. Method Definition: Boolean contentEquals(StringBuffer sb) Return Type: It returns true if the content is equal to the stated string else it returns false. Example #1: // Scala program of contentEquals() // method // Creating object object GfG { // Main method
1 min read
Scala Keywords
Keywords or Reserved words are the words in a language that are used for some internal process or represent some predefined actions. These words are therefore not allowed to use as variable names or objects. Doing this will result in a compile-time error. Example: // Scala Program to illustrate the keywords // Here object, def, and var are valid ke
2 min read
Scala Int /(x: Int) method with example
The /(x: Int) method is utilized to return the quotient when the specified first int value is divided by the second int value. Method Definition: (First_Int_Value)./(Second_Int_Value) Return Type: It returns the quotient when the specified first int value is divided by the second int value. Example #1: // Scala program of Int /(x: Int) // method //
1 min read
Scala Int /(x: Short) method with example
The /(x: Short) method is utilized to return the quotient when the specified int value is divided by the short value. Method Definition: (Int_Value)./(Short_Value) Return Type: It returns the quotient when the specified int value is divided by the short value. Example #1: // Scala program of Int /(x: Short) // method // Creating object object GfG {
1 min read
Program to print Java Set of characters in Scala
A java Set of characters can be returned from a Scala program by writing a user defined method of Java in Scala. Here, we don't even need to import any Scala’s JavaConversions object in order to make this conversions work. Now, lets see some examples. Example:1# // Scala program to print Java Set // of characters in Scala // Creating object object
2 min read
Scala Map size() method with example
The size() is utilized to find the number of key-value pairs in the stated map. Method Definition: def size: Int Return Type: It returns the number of elements in the map. Example #1: // Scala program of size() // method // Creating object object GfG { // Main method def main(args:Array[String]) { // Creating a map val m1 = Map(3 -&gt; &quot;geeks
1 min read
Scala SortedMap addString() method with a start, a separator and an end with example
This method is same as addString() method but here a start, a separator and an end is also included. Method Definition: def addString(sb: mutable.StringBuilder, start: String, sep: String, end: String): mutable.StringBuilder Where, sep is the separator stated. Return Type: It returns the elements of the SortedMap in the String Builder and a start,
2 min read
Scala Iterator addString() method with example
The addString() method belongs to the concrete value members of the class AbstractIterator. It is defined in the class IterableOnceOps. It is utilized to append the elements of the Scala Iterator to a String Builder. Method Definition : def addString(b: StringBuilder): StringBuilder Return Type : It returns the String Builder to which the elements
1 min read
Scala String substring(int beginIndex, int endIndex) method with example
The substring(int beginIndex, int endIndex) method is utilized to find the sub-string from the stated String which starts and ends with the index specified. Method Definition: String substring(int beginIndex, int endIndex) Return Type: It returns string which is the part of the stated String. Note: It is same as sub-sequence method but the only dif
1 min read
Program to convert Java list to an iterator in Scala
A java list can be converted to an iterator in Scala by utilizing toIterator method of Java in Scala. Here, we need to import Scala’s JavaConversions object in order to make this conversions work else an error will occur. Now, lets see some examples and then discuss how it works in details. Example:1# C/C++ Code // Scala program to convert Java lis
3 min read
Scala Set &amp;() method with example
The &amp;() method is utilized to create a new set consisting of all elements that are present in both the given sets. Method Definition: Return Type: It returns a new set consisting of all elements that are present in both the given sets. Example #1: // Scala program of &amp;() // method // Creating object object GfG { // Main method def main(args
1 min read
Scala | Type Inference
Scala Type Inference makes it optional to specify the type of variable provided that type mismatch is handled. With type inference capabilities, we can spend less time having to write out things compiler already knows. The Scala compiler can often infer the type of an expression so we don’t have to declare it explicitly. Let us first have a look at
4 min read
Program to convert Java set of Shorts to an Indexed Sequence in Scala
A java set of Shorts can be converted to an Indexed Sequence in Scala by utilizing toIndexedSeq method of Java in Scala. Here, we need to import Scala’s JavaConversions object in order to make this conversions work else an error will occur. Now, lets see some examples and then discuss how it works in details. Example:1# // Scala program to convert
2 min read
Scala Int &lt;(x: Char) method with example
The &lt;(x: Char) method is utilized to return true if the specified int value is less than the char value, otherwise returns false. Here the char value is the ASCII value of the specified char. Method Definition: (Int_Value).&lt;(Char_Value)Return Type: It returns true if the specified int value is less than the char value, otherwise returns false
1 min read
Scala Int &lt;=(x: Double) method with example
The &lt;=(x: Double) method is utilized to return true if the specified int value is less than or equal to the double value, otherwise returns false. Method Definition: (Int_Value).&lt;=(Double_Value) Return Type: It returns true if the specified int value is less than or equal to the double value, otherwise returns false. Example #1: // Scala prog
1 min read
Article Tags :