In this article, we will see how to create functions in Kotlin.
Kotlin functions
Kotlin functions are created using the fun keyword.
Kotlin function example
fun main(args: Array<String>) { val num1=10 val num2=11 val result = sum(num1, num2) println("Sum is $result") } fun sum(param1:Int, param2:Int) : Int { return param1 + param2 }
Creating functions with Named parameters
With named parameters, we can pass them in any order.
Kotlin function with named parameter example
fun main(args: Array<String>) { val num1=10 val num2=11 val result = diff(param2=num2, param1=num1) println("Difference is $result") // Difference is -1 } fun diff(param1:Int, param2:Int) : Int { return param1 - param2 }
Function parameters are immutable
As function parameters are immutable, we can’t directly change them. We can create a copy and make updates on it.
fun main(args: Array<String>) { val num1=10 diff(num1) } fun doSomething(param:Int) { return param++ // error : Val cannot be reassigned }
© 2018, https:. All rights reserved. On republishing this post, you must provide link to original post