Scala nested methods

 214 total views,  3 views today

Welcome to Scala series. This tutorial is about the Scala nested methods.

A method in Scala (or in any programming language) is list of statements in a sequence order to perform a certain task.

You can checkout this post to learn more about Scala methods.

Syntax of a method

def methodname(arguments):returnType = {
 //statements
}

A method can have any number of nested method inside the method block.Scala supports nested methods. The scope of the nested methods are available within parent method and it cannot be accessed outside.

Syntax of a nested method

def methodname(arguments):returnType = {
 //statements
   def add(arguments):returnType = {
     //statements
   }
   def divide(arguments):returnType = {
     //statements
   }
}

Scala nested method example

object Staticreference {

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

    var i = 10;

    println(add(i)); //call add
    println(sub(i)); //call sub

    def add(x: Int): Int = {
      x + 10;
    }

    def sub(x: Int): Int = {
      x - 2;
    }

  }
}

Output

20
8

Multi-level nested method

object Staticreference {

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

    var i = 10;

    println(add(i)); //call add
    println(sub(i)); //call sub

    def add(x: Int): Int = {

      def add20(y: Int): Int = {

        def add30(z: Int): Int = {

          z + 30
        }
        add30(y) + 20
      }
      add20(x) + 10;
    }

    def sub(x: Int): Int = {
      x - 2;
    }

  }
}

Output

70
8

References: Official documentation

Thanks for reading and hope you like this tutorial. Please leave a comment and give us a thumbs up!

Tags :

About the Author

Rajasekar

Hey There, My name is Rajasekar and I am the author of this site. I hope you are liking my tutorials and references. Programming and learning new technologies are my passion. The ultimate idea of this site is to share my knowledge(I am still a learner :)) and help you out!. Please spread your words about us (staticreference.com) and give a thumbs up :) Feel free to contact me for any queries!.