Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Extension and Infix Functions | Kotlin Idioms and Control Flow
Kotlin for Java Developers

bookExtension and Infix Functions

Свайпніть щоб показати меню

Kotlin allows you to enhance the functionality of existing classes without modifying their source code by using extension functions. An extension function lets you "add" new functions to classes, including classes from the standard library or Java, as if they were part of the original class. This is especially useful for utility methods or for adapting APIs in a more idiomatic way.

Infix notation in Kotlin enables you to call certain functions using a syntax that omits the dot and parentheses, making code more readable and expressive. To use infix notation, a function must be marked with the infix keyword and must be a member or extension function with a single required parameter.

Practical use cases include:

  • Adding custom utility methods to standard types, such as formatting or validation methods for String or Int;
  • Creating domain-specific languages (DSLs) or fluent APIs by leveraging infix functions for natural, readable code;
  • Improving code expressiveness by chaining extension and infix functions for concise transformations or operations.
ExtensionInfixDemo.kt

ExtensionInfixDemo.kt

copy
123456789101112131415161718
package com.example // Extension function for String: capitalize the first letter fun String.capitalizeFirst(): String = if (this.isNotEmpty()) this[0].uppercase() + this.substring(1) else this // Infix extension function for Int: check if in range infix fun Int.isBetween(range: IntRange): Boolean = this in range fun main() { val original = "kotlin" println("Original: $original") println("Capitalized: ${original.capitalizeFirst()}") val number = 7 val result = number isBetween 5..10 println("Is $number between 5 and 10? $result") }

In this code, you define an extension function capitalizeFirst for the String class. This function checks if the string is not empty and then capitalizes its first letter, returning the modified string. You can call this method on any String instance as if it were a native method, which demonstrates how extension functions let you enhance existing types in a natural, readable manner.

Next, you define an infix extension function isBetween for the Int class. The infix keyword allows you to write number isBetween 5..10 instead of number.isBetween(5..10). This makes range checks read almost like natural language, enhancing code clarity, especially when building DSL-like APIs or writing validation logic.

Both extension and infix functions contribute to code expressiveness by letting you write concise, readable, and intention-revealing code that feels like a natural extension of the language itself.

question mark

What is the purpose of an extension function in Kotlin?

Select the correct answer

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 3. Розділ 4

Запитати АІ

expand

Запитати АІ

ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

Секція 3. Розділ 4
some-alt