Search⌘ K

Declaring Functions

Explore the essential components of declaring functions in Kotlin. Understand the use of the fun keyword, parameter syntax, return types, and Kotlin-specific features like vararg and top-level functions. This lesson helps you grasp Kotlin’s streamlined function declaration style for clearer, more concise code.

Introduction

This is what the declaration of listOf in Kotlin really looks like:

public fun <T> listOf(vararg elements: T) : List<T>

Let’s go through this step by step:

The public keyword is no surprise for Java professionals.

However, the second keyword, fun, lets even experienced Java users down because there is no fun in Java (well, at least not as much as in Kotlin!).

Kotlin’s fun keyword

Just like variable declarations initiated with their own keywords (var or val), functions are also declared with a specific keyword. Its name, fun, stands for function.

The return type is last

...