Functions

We saw our first Kotlin function several chapters ago:

  println("hello, world!")

Now, let’s explore functions in greater detail, as they offer a number of features that are not quite as common among the peer set of languages that we are comparing Kotlin to (Java, Ruby, JavaScript).

Functions with Parameters

Our main() functions have had no parameters. However, functions can take parameters, and most functions that you will write will wind up with one or more parameters:

fun main() {
  lessTrivial(1, 1)
}

fun lessTrivial(left: Int, right: Int) {
  println(left + right)
}

In the function declaration, a parameter is a name, followed by a colon, followed by a type. The function declaration can have no parameters, a single parameter, or a comma-delimited list of parameters. So, here, we have two parameters, named left and right, that are both of type Int.

The default approach for calling such a function is to simply provide values for those parameters, in the same order as those parameters appear in the function declaration. That is what we are doing with our lessTrivial(1, 1) call. However, as we will see later in this chapter, there are alternative ways of calling this function.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.