Extension and Infix Functions
Veeg om het menu te tonen
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
StringorInt; - 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
123456789101112131415161718package 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.
Bedankt voor je feedback!
Vraag AI
Vraag AI
Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.