Kotlin Infix Functions : Simplify Your Codebase

Home » Kotlin » Kotlin Infix Functions : Simplify Your Codebase

One of the lesser-known gems in the Kotlin language is the concept of infix functions. Infix functions enable developers to write more expressive code by allowing certain functions to be called using infix notation, resulting in cleaner and more readable code.We will explore the power of Kotlin infix functions.

Kotlin Infix Functions : Simplify Your Codebase

Understanding Kotlin Infix Functions

In Kotlin, an infix function is a member function or an extension function that has a single parameter. The unique aspect of infix functions is that they can be called using infix notation, where the function name appears in between the object and the argument.

Syntax and Usage

To define an infix function, you need to use the infix modifier before the function declaration.

infix fun objectName.functionName(parameter: Type): ReturnType {
    // Function body
}

Infix functions are particularly useful when working with mathematical expressions. You can define infix functions for mathematical operations like addition, subtraction, multiplication, or even custom operators, making your code resemble the mathematical notation more closely.

Infix functions enable you to define your own DSLs, which can greatly simplify complex tasks. For example, you can create a DSL for querying databases, configuring network requests, or defining UI layouts.

Kotlin Infix Function Example

Let’s consider a simple example of a custom infix function that checks whether a string contains another string.

Open the Kotlin Playground and Write the following code.

fun main() {
    val text = "Hi, Nikki"
    val contains = text containString "Nikki"  // true
    val no_item = text containString "HI" // false
    println(contains)
    println(no_item)
    
    
}

infix fun String.containString(other: String): Boolean
{
    return this.contains(other)
}

Output

true
false

In this example, the containsString function can be called using infix notation, resulting in cleaner and more readable code.Infix functions provide a more natural and readable syntax, making your code more expressive.

Infix notation

Functions marked with the infix keyword can also be called using the infix notation.

The following requirements must be met by infix functions:

  1. In order to be considered infix functions, they must either be member functions or extension functions.

2. A crucial requirement for infix functions is that they should have exactly one parameter.

3. The parameter of an infix function must not accept a variable number of arguments and should not have any default value assigned to it.

You may also like...