Skip to content

Beginner: Kotlin · Null safety, functions and lambdas · topic 6 of 50 · 30 min

Functions

Explanation

Functions are declared with fun, a name, typed parameters and an optional return type after a colon. A function that returns nothing returns Unit. Short functions can be written as a single expression with =. Default and named arguments make calls clear and remove the need for many overloads; vararg accepts any number of values.

Why functions?

A function is a named, reusable block of code that does one job. Instead of repeating the GST calculation in ten places, you write it once as a function and call it ten times. If the rule changes, you fix one place.

kotlin
fun withGst(price: Double, ratePercent: Double): Double {
    return price + price * ratePercent / 100
}

fun main() {
    val total = withGst(1000.0, 18.0)
    println(total)       // 1180.0
}
Parameters are written name: Type. The return type follows the parentheses after a colon.

Unit: returning nothing

A function that only does something (like printing) and returns no useful value has the return type Unit. You can leave it out: fun greet(name: String) { ... } is the same as fun greet(name: String): Unit { ... }.

Single-expression functions

If a function just returns one expression, write = and the expression, without braces or return. Kotlin infers the return type. This style is very common.

kotlin
fun square(n: Int) = n * n
fun isAdult(age: Int) = age >= 18
fun grade(marks: Int) = if (marks >= 33) "Pass" else "Fail"
Short, readable, and the return types (Int, Boolean, String) are inferred.

Default arguments

A parameter can have a default value. Callers may leave it out. In Java you would write several overloaded versions; in Kotlin one function is enough.

kotlin
fun ticket(from: String, to: String, passengers: Int = 1, classType: String = "Sleeper") =
    "$passengers x $classType: $from to $to"

fun main() {
    println(ticket("Pune", "Nagpur"))                  // 1 x Sleeper: Pune to Nagpur
    println(ticket("Pune", "Nagpur", 3))               // 3 x Sleeper: Pune to Nagpur
    println(ticket("Pune", "Nagpur", classType = "3A")) // 1 x 3A: Pune to Nagpur
}
The last call skips passengers and sets classType by name.

Named arguments

You can name arguments when calling: sendSms(to = "98...", text = "Hi", urgent = true). Named arguments make calls with many parameters, especially Booleans, much easier to read, and you can give them in any order. Jetpack Compose code uses named arguments everywhere.

vararg: any number of arguments

kotlin
fun total(vararg prices: Int): Int {
    var sum = 0
    for (p in prices) sum += p
    return sum
}

fun main() {
    println(total(120, 80, 45))     // 245
    println(total())                // 0
}
Inside the function, prices behaves like an array.

Top-level and local functions

Kotlin functions do not need to live inside a class. A function written directly in a file is a top-level function, usable from anywhere in the module. You can also define a function inside another function (a local function) for a small helper that nobody else needs.

Think of it like this: Default arguments are like a restaurant's standard thali. You get the usual unless you say otherwise: "one thali" gets the defaults, "one thali, extra roti" changes just that part. Named arguments are like saying exactly what you want changed, so the waiter never confuses rotis with rice.

Common mistakes

  • Forgetting the return type when using braces and return: the function then returns Unit, and return value is an error. Add : Type.
  • Using return inside a single-expression function body. With =, there is no return keyword.
  • Positional Boolean arguments like save(true, false). Use named arguments: save(sync = true, notify = false).
  • Mixing named and positional arguments in a confusing order. Keep positional ones first.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Functions · 1/6

fun name(param: Type): ReturnType

A function is a named block of code that does one job. You write it once and call it many times.

Prefer a video by a teacher? Find free videos on “kotlin functions default named arguments single expression” on YouTube ↗

In real life: Formatting rupee amounts

An expense-tracker app shows money everywhere: lists, totals, charts. One function formatRupees(amount, showPaise = true) is used on every screen. Most screens use the default, while the chart labels call formatRupees(x, showPaise = false) for shorter text.

kotlin
fun formatRupees(paise: Long, showPaise: Boolean = true): String {
    val rupees = paise / 100
    val rest = paise % 100
    return if (showPaise) "Rs $rupees.${rest.toString().padStart(2, '0')}" else "Rs $rupees"
}

fun main() {
    println(formatRupees(123456))                    // Rs 1234.56
    println(formatRupees(123456, showPaise = false)) // Rs 1234
}
padStart(2, '0') turns 5 into "05".

Practice (0/3 done)

Task 1 · Question

What does this print? fun greet(name: String, greeting: String = "Hello") = "$greeting, $name!" fun main() { println(greet("Ira", greeting = "Namaste")) }

Task 2 · Question

What is the return type of fun log(msg: String) { println(msg) }?

Task 3 · Practice

Write fun emi(principal: Double, yearlyRate: Double = 9.0, months: Int = 12): Double. Call it three ways: with only principal, with principal and months by name, and with all three. Then write fun average(vararg marks: Int): Double that returns 0.0 for no marks.

Quick quiz

Question 1

1.Which is a valid single-expression function?

Question 2

2.Why are named arguments useful?

Question 3

3.Inside fun f(vararg n: Int), what does n behave like?

Question 4

4.Do Kotlin functions have to be inside a class?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

Which is a valid single-expression function?

Answer: fun double(x: Int) = x * 2

Use = with an expression; parameter types are required.

Why are named arguments useful?

Answer: They make calls with many parameters clear and order-independent

Names document what each value means.

Inside fun f(vararg n: Int), what does n behave like?

Answer: An array of Int

vararg parameters are arrays inside the function.

Do Kotlin functions have to be inside a class?

Answer: No, top-level functions are allowed

Kotlin supports top-level functions.

Can you overload two methods that differ only in return type?Related

Answer: No, the parameter lists must differ

The compiler chooses an overload by arguments, so return type alone is not enough (CS0111).

From Parameters in depth: optional, named, ref, out, params, overloading

What does a function without -> return?Related

Answer: The unit type ()

Without a return type, the function returns ().

From Functions, statements and expressions

A variable is declared with const inside a function. Where can it be used?Related

Answer: Only inside that function

let and const are block-scoped: they live only inside their { }.

From Functions

function f() { return 1; console.log("hi"); } What happens when f() runs?Related

Answer: Returns 1 and never prints

return ends the function; the next line is never reached.

From Functions: declarations, expressions and return

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 2 more topics in “Null safety, functions and lambdas” before its exam: Lambdas and higher-order functions, Extension functions and scope functions.
  2. Module 2 exam: Null safety, functions and lambdas · 13 questions · 20 min, without help. 4 topics of this module still to finish first.
  3. Then the next module, Classes, objects and collections. 50 topics left in the course before the final exam.

← Previous: Null safety