Infix and Inline Functions in Kotlin

1. Why Use Infix and Inline Functions?

Kotlin provides infix and inline functions to improve code readability, conciseness, and performance.

Together, these features make Kotlin code expressive, readable, and efficient.


2. Infix Functions

An infix function is a function that can be called using infix notation — without parentheses or the dot . operator.

Requirements for Infix Functions
Basic Infix Function Example

// Extension function with infix notation
infix fun Int.times(str: String) = str.repeat(this)

fun main() {
    val result = 3 times "Hi "
    println(result) // Output: Hi Hi Hi 
}
    
Using Infix with Classes

class Person(val name: String) {
    infix fun likes(other: Person) = "${this.name} likes ${other.name}"
}

fun main() {
    val alice = Person("Alice")
    val bob = Person("Bob")

    println(alice likes bob) // Output: Alice likes Bob
}
    

3. Inline Functions

An inline function tells the compiler to insert the function's code directly at the call site instead of creating a function object. This improves performance, especially when using lambdas as parameters.

Basic Inline Function Example

inline fun operate(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
    return operation(a, b)
}

fun main() {
    val sum = operate(5, 3) { x, y -> x + y }
    println(sum) // Output: 8
}
    

Benefit: The lambda { x, y -> x + y } is inserted directly into the call site, avoiding lambda object creation.

Inline Function with Reified Type

Inline functions can also use reified type parameters to access type information at runtime, which is not normally available due to type erasure.


inline fun  isType(value: Any): Boolean {
    return value is T
}

fun main() {
    println(isType("Hello")) // Output: true
    println(isType("Hello"))    // Output: false
}
    

4. Combining Infix and Inline Functions

You can also declare a function as both infix and inline for a clean syntax and optimized performance.


inline infix fun Int.shout(message: String) = println("$message!".repeat(this))

fun main() {
    3 shout "Wow" 
    // Output: Wow!Wow!Wow!
}
    

5. When to Use and When Not to Use

✅ Use Infix Functions When:
✅ Use Inline Functions When:
🚫 Avoid When:

6. Common Interview Questions


7. Example Program


// Infix and Inline combined example
inline infix fun String.repeatMessage(times: Int) = this.repeat(times)

fun main() {
    val message = "Hello " repeatMessage 3
    println(message) // Output: Hello Hello Hello 
}
    

Summary:
Infix and inline functions make Kotlin code more readable, expressive, and efficient. Infix functions provide natural syntax for single-parameter functions, while inline functions optimize performance and enable reified types. Using them effectively improves code clarity, performance, and developer productivity.