In Scala, you can nest methods and functions inside a method. This is a useful feature when you want to encapsulate a part of the logic specific to the enclosing method. The following is an example of a nested method.
1 2 3 4 5 6 7 |
def mainMethod (x: String) = { def nestedMethod(y:String, z: String) = { println(y + z) } nestedMethod(x," a nested method") } println(mainMethod("I am")) |
When you run this code, it will print ‘I am a nested function’.
Similarly, you can do nested functions as below.
1 2 3 4 5 6 |
def mainMethod (x: String) = { val nestedFucntion = (y: String, z: String) => println(y + z) nestedFucntion(x," a nested function") } println(mainMethod("I am")) |