Functions with parameters and return types

Functions can receive parameters and return values as a result. See the following example, which takes a value as a parameter and returns the result:

fun myFun(message : String) : String {
return "Hello from $message"
}

fun main (args: Array<String>){
val result = myFun("Author")
println(result)
}

This function takes a string as a parameter and returns a string value. Like other programming languages, Kotlin also uses the return keyword to return a value from a function. The return value must be the same as the return type defined in the function signature:

fun add(i: Int, j: Int): Int

If a return type of the function is integer, the return statement must be an integer, otherwise the compiler will throw an error. Here is an example of a function called addValues. This takes two integer parameters, adds them, and returns an integer as a result:

fun addValues(i: Int, j: Int): Int{
val k = i + j
return k
}

fun main (args: Array<String>) {
val result = addValues(5,6)
println(result)
}

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.138.178