Mobile Development 17 min read

Kotlin Function Features: Expression Bodies, Named & Default Arguments, Top‑Level & Extension Functions, Lambdas, Member References, with/apply

Kotlin’s function features—including expression bodies, named and default arguments, top‑level and extension functions, local functions, lambdas, member references, and the utility functions with and apply—enable Android developers to write concise, expressive, and boiler‑plate‑free code.

vivo Internet Technology
vivo Internet Technology
vivo Internet Technology
Kotlin Function Features: Expression Bodies, Named & Default Arguments, Top‑Level & Extension Functions, Lambdas, Member References, with/apply

Kotlin has become the official language for Android development. The article introduces several Kotlin function features that help reduce boilerplate and improve code safety.

1. Expression function bodies

Simple functions can be written as a single expression, e.g.:

fun max(a: Int, b: Int) = if (a > b) a else b

2. Named arguments

Arguments can be passed by name and in any order, which makes calls clearer:

joinToString(separator = " ", collection = list, postfix = "}", prefix = "{")

3. Default parameters

Parameters can have default values, allowing callers to omit them:

fun
joinToString(
    collection: Collection
,
    separator: String = " ",
    prefix: String = "[",
    postfix: String = "]"
): String { … }

// Call with only the collection
joinToString(list)

4. Top‑level functions

Kotlin allows functions to be defined outside of classes. After compilation they become static methods in a generated class (e.g., JoinKt ).

// file: join.kt
package strings
fun joinToString() : String { … }

// Java usage
import strings.JoinKt;
JoinKt.joinToString();

5. Extension functions

Functions can be added to existing types without modifying the original class. They are compiled as static methods that receive the receiver as the first argument.

fun
Collection
.joinToString(
    separator: String = " ",
    prefix: String = "[",
    postfix: String = "]"
): String {
    val sb = StringBuilder(prefix)
    for ((index, element) in this.withIndex()) {
        if (index > 0) sb.append(separator)
        sb.append(element)
    }
    sb.append(postfix)
    return sb.toString()
}

val list = arrayListOf("10", "11", "1001")
println(list.joinToString()) // [10 11 1001]

6. Local functions

Functions can be declared inside other functions to avoid code duplication:

fun saveUser(user: User) {
    fun validate(value: String, fieldName: String) {
        if (value.isEmpty()) {
            throw IllegalArgumentException("Can't save user ${user.id}: empty $fieldName")
        }
    }
    validate(user.name, "Name")
    validate(user.address, "Address")
}

7. Lambda expressions

Lambdas are anonymous functions that can be passed as values. Example:

val sum = { x: Int, y: Int -> x + y }
println(sum(1, 2))

run { println(42) }

Lambdas can be used with collection operations, e.g., people.maxBy { it.id } , and can capture surrounding variables.

8. Member references

Instead of writing a lambda that simply calls a function, a member reference can be used:

people.maxBy(User::id)

fun salute() = println("Salute!")
run(::salute)

References also work for constructors ( ::Person ) and extension functions ( Person::isAdult ).

9. with and apply

The with function executes a block with a receiver object and returns the block result:

@kotlin.internal.InlineOnly
public inline fun
with(receiver: T, block: T.() -> R): R = receiver.block()

Example using StringBuilder :

fun alphabet(): String = with(StringBuilder()) {
    for (letter in 'A'..'Z') {
        append(letter)
    }
    append("\nNow I know the alphabet!")
    toString()
}

The apply function is similar but always returns the receiver object:

@kotlin.internal.InlineOnly
public inline fun
T.apply(block: T.() -> Unit): T { block(); return this }

fun alphabet() = StringBuilder().apply {
    for (letter in 'A'..'Z') {
        append(letter)
    }
    append("\nNow I know the alphabet!")
}.toString()

10. Summary

The article covered a subset of Kotlin’s function capabilities—expression bodies, named/default arguments, top‑level and extension functions, local functions, lambdas, member references, and the utility functions with and apply . These features help Android developers write concise, expressive code and reduce boilerplate.

mobile developmentlambdaKotlinfunctionsapplyExtension Functionswith
vivo Internet Technology
Written by

vivo Internet Technology

Sharing practical vivo Internet technology insights and salon events, plus the latest industry news and hot conferences.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.