Creating Functions
We'll cover the following...
Creating functions, and methods, in Kotlin is refreshingly different from creating methods in Java. The greater flexiblity that Kotlin offers removes unnecessary ceremony when creating functions. Let’s start with short functions, explore type inference, and then look at defining parameters and multiline functions.
KISS functions
Kotlin follows the mantra “Keep it simple, stupid”—the KISS principle—to function definitions. Small functions should be simple to write, no noise, no fluff. Here’s one of the shortest functions you can write in Kotlin, followed by a call to it.
fun greet() = "Hello"println(greet())
Function declarations start with the keyword fun
—Kotlin wants you to remember to have fun every time you look at a function or a method. The function name is followed by a parameter list, which may be empty. If the function is a single-expression function, which is very short, then separate the body from the declaration using the =
operator instead of using the {}
block syntax. For short functions, the return type can be inferred. Also, the return
keyword isn’t allowed for single-expression functions, which are functions without a block body.
Run this script to see Kotlin greet you:
Hello
Let’s examine what the above function actually returns.
Return type and type inference
The greet()
function returns a String
, but we didn’t explicitly specify that. That’s because Kotlin can infer the return type of functions with a non-block body—that is, functions without {}
. The return type inference happens at compile time. Let’s verify this by making a mistake in code:
fun greet() = "Hello"
val
...