iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🔡

Idiomatic Syntax Features in Kotlin

に公開
2025/12/25

This article is the 7th entry of the Programming Language Specific Syntax Advent Calendar 2025.

I will introduce some features with a personal touch.

Binary Search Sample Code

I have implemented this by intentionally utilizing language-specific features.

// Kotlin - when expression + destructuring declaration + scope functions
fun <T : Comparable<T>> binarySearch(arr: List<T>, target: T): Int {
    var (left, right) = 0 to arr.lastIndex

    while (left <= right) {
        val mid = (left + right) ushr 1
        val (newLeft, newRight) = when {
            arr[mid] == target -> return mid
            arr[mid] < target -> (mid + 1) to right
            else -> left to (mid - 1)
        }
        left = newLeft
        right = newRight
    }
    return -1
}

fun main() {
    val arr = listOf(1, 3, 5, 7, 9)
    println(binarySearch(arr, 5))  // 2
}

when expression

A branching expression with pattern matching more powerful than a switch statement.

// A powerful alternative to switch statements
val result = when (x) {
    1 -> "one"
    2, 3 -> "two or three"
    in 4..10 -> "4 to 10"
    is String -> "string"
    else -> "other"
}

// Branching without an argument
when {
    x < 0 -> "negative"
    x > 0 -> "positive"
    else -> "zero"
}

Bitwise Operators

(0b1010 ushr 1) // Unsigned right shift
(0b1010 shl 1)  // Left shift
(0b1010 inv())  // Bitwise inversion
(0b1010 and 0b1100) // AND
(0b1010 or 0b1100)  // OR
(0b1010 xor 0b1100) // XOR

Shift operators are also provided.
There are many top-level functions.

Destructuring Declarations

You can assign values from a Pair or data class to multiple variables at once.

// Destructuring Pairs and data classes
val (left, right) = 0 to 10
val (name, age) = person

// Iterating over a map
for ((key, value) in map) {
    println("$key: $value")
}

This is equivalent to .entries or enhanced for loops.

Scope Functions

A set of functions (let, apply, run, also) that execute a code block within the scope of an object.

// let: null check + conversion
val length = str?.let { it.length } ?: 0

// apply: object configuration
val person = Person().apply {
    name = "Alice"
    age = 30
}

// run: execute block
val result = run {
    val x = compute()
    x * 2
}

// also: side effects
list.also { println("count: ${it.size}") }

Extension Functions

You can add new methods to existing classes without modifying them.

// Adding methods to an existing class
fun String.addExclamation() = this + "!"

"Hello".addExclamation()  // "Hello!"

// Combining with generics
fun <T> List<T>.secondOrNull(): T? = getOrNull(1)

Elvis Operator ?:

An operator that provides a default value when a variable is null.

// Default value when null
val name = user?.name ?: "anonymous"

// Early return
val value = getValue() ?: return
val length = str?.length ?: throw IllegalArgumentException()

Infix Functions

You can define functions that can be called using infix notation.

// Functions callable with infix notation
infix fun Int.times(str: String) = str.repeat(this)
3 times "Hi "  // "Hi Hi Hi "

// Examples from the standard library
0 to 10        // Pair(0, 10)
1 until 10     // 1..9
list zip other // list of pairs

I feel like this existed in Ruby too, but it is not very common in other languages.

GitHubで編集を提案

Discussion