热门面试题与答案和在线测试
面向面试准备、在线测试、教程与实战练习的学习平台

通过聚焦学习路径、模拟测试和面试实战内容持续提升技能。

WithoutBook 将分主题面试题、在线练习测试、教程和对比指南整合到一个响应式学习空间中。

Chapter 5

Functions, Default Arguments, Lambdas, and Extension Functions

Move from simple statements to reusable logic with functions, named arguments, higher-order functions, lambdas, and one of Kotlin’s signature features: extension functions.

Inside this chapter

  1. Basic Functions
  2. Default and Named Arguments
  3. Lambdas and Higher-Order Functions
  4. Extension Functions
  5. Single-Expression Functions
  6. Real-Time Example

Series navigation

Study the chapters in order for the clearest path from Kotlin setup and syntax to coroutines, backend work, clean design, multiplatform thinking, and advanced engineering practice. Use the navigation at the bottom to move smoothly through the full tutorial series.

Tutorial Home

Chapter 5

Basic Functions

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

Functions are the first step toward clean program structure. They help isolate logic, improve readability, and make testing easier.

Chapter 5

Default and Named Arguments

fun greet(name: String, prefix: String = "Hello"): String {
    return "$prefix, $name"
}

println(greet(name = "Anita"))
println(greet(name = "Anita", prefix = "Welcome"))

This feature reduces overloaded method clutter and makes call sites clearer.

Chapter 5

Lambdas and Higher-Order Functions

val numbers = listOf(1, 2, 3, 4)
val doubled = numbers.map { it * 2 }

Kotlin uses higher-order functions heavily, especially in collections APIs, asynchronous callbacks, builders, and DSL design.

Chapter 5

Extension Functions

fun String.initials(): String {
    return split(" ")
        .filter { it.isNotBlank() }
        .joinToString("") { it.first().uppercase() }
}

println("Riya Sen".initials())

Extension functions allow developers to add utility behavior in a natural way without modifying the original class source. They are common in Android utilities, backend helper modules, and reusable libraries.

Chapter 5

Single-Expression Functions

fun square(x: Int) = x * x

This syntax keeps simple logic concise and readable.

Chapter 5

Real-Time Example

In an online booking platform, functions may validate traveler details, compute fare breakdowns, format itinerary data, and trigger downstream calls. Strong function design prevents business logic from turning into a long unreadable block.

版权所有 © 2026,WithoutBook。