Creating Functions

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 ...

Get Programming Kotlin now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.