Functions with Return Types
The functions shown so far are Kotlin’s equivalent of Java methods that return void
, in that they are not returning any values to the caller.
(technically, they are returning Unit
, which we will explore later in the book)
However, as with functions and methods in most programming languages, Kotlin functions can return values, using the return
keyword:
fun main() {
println(simpleReturn(1, 1))
}
fun simpleReturn(left: Int, right: Int) : Int {
return left + right
}
However, to be able to return a value, the function needs to declare the type of what is being returned. In many languages, such as Java, that “return type” is declared at the beginning of the function declaration. In Kotlin, it is declared at the end, after the closing parenthesis, separated by a colon. So, here, we are returning an Int
, by virtue of that : Int
after the fun simpleReturn(left: Int, right: Int)
part.
Code that calls the function then can use that returned value. In the above code snippet, we are printing it to standard output. You could also store it in a variable:
fun main() {
val result = simpleReturn(1, 1)
println(result)
}
fun simpleReturn(left: Int, right: Int) : Int {
return left + right
}
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.