Friday, 2 February 2018

Kotlin: Local functions

In kotlin, you can define a function inside other function.

Ex
fun factorial(n: Int): Int {
         fun fact(n: Int): Int {
                 if (n == 0) return 1
                 return n * fact(n - 1)
         }

         if (n < 0) return -1
         else return fact(n)
}

As you see above snippet, I defined fact inside the factorial function. ‘fact’ is the local function, whereas factorial is the outer function.

FunctionDemo.kt
fun factorial(n: Int): Int {
 fun fact(n: Int): Int {
  if (n == 0) return 1
  return n * fact(n - 1)
 }

 if (n < 0) return -1
 else return fact(n)
}

fun main(args: Array<String>) {

 var factorialOf5 = factorial(5)

 println("factorial Of 5 : $factorialOf5")
}

Output
factorial Of 5 : 120


Local functions can access the data defined in outer functions.

Previous                                                 Next                                                 Home

No comments:

Post a Comment