Instruction

In Kotlin, you can create a function using the fun keyword. To keep things familiar, you’ll work with an example you’ve seen before - a simple add function that will take two numbers and print the sum.

Here’s what that looks like:

fun add(a: Int, b: Int) {
  println(a+b)
}

add(7, 2) //prints 9
add(10, 5) //prints 15

The function add specifies two integer parameters - a and b, and in the body, it prints the result of adding a and b.

Returning Values

Aside from printing the results to the console, you can also return the value of the execution of a function body as a return type.

You can specify the type at the end of the function signature. The add() can be modified to do so as follows:

fun add(a: Int, b: Int): Int {
  return a+b
}

val result = add(20, 20)
println(result)

Note: All functions have a return type Unit, even the ones that don’t return anything. The previous version of the add function returns Unit, but you don’t need to specify this in the function signature.

Using Single Expression Functions

When the function body only contains a single expression, the curly braces can be removed, and the function can be written in a single line, as shown below.

fun add(a: Int, b: Int) = a + b

println(add(5, 10)) //prints 15

This syntax greatly enhances the readability of files that contain several utility functions that perform basic operations.

Utilzing Named Arguments

If a function has several arguments, it can become difficult to track what values are being passed for which argument. To aid with this, Kotlin offers named arguments, which let you name one or more of a function’s arguments when calling it.

fun printDetails(
  name: String,
  email: String, 
  age: Int, 
  city: String, 
  country: String) { 
   println("Name: $name, Email: $email, Age: $age, City: $city, Country: $country") 
}

printDetails("Jane", "jane@gmail.com", 23, "LA", "USA") //can become difficult to infer

printDetails(
name = "Jane", 
email = "jane@gmail.com", 
age = 23,
city = "LA", 
country = "USA") // more readable

An added benefit of using named arguments is the ability to specify the values in any order. Here’s what that looks like:

printDetails(
age = 43,
email = "jack@gmail.com", 
city = "MA", 
name = "Jack", 
country = "USA") 

To make functions even more versatile and flexible, Kotlin offers the ability to specify default values for some or all of its parameters. With default values, you can skip certain values as needed.

Here’s a quick example:

fun greet(greeting: String = "Hello", name: String) {
  println("$greeting $name!")
}

greet(name = "Jack") //prints Hello Jack!
greet("Howdy", "Jane") //prints Howdy Jane!

In the snippet above, if a value isn’t specified for the greeting parameter, the default value will be used.

See forum comments
Download course materials from Github
Previous: Introduction Next: Demo