🏎️ · Infix Functions

2 min read · Updated on by

Kotlin allows you to define infix functions, giving you the ability to call functions in an infix manner (i.e. the function name goes between the operands). A great example is the to function, which we mentioned briefly in the article on data classes. It creates a Pair<A, B> from its left and right operands. At it's core, it's nothing but syntactic sugar allowing you to omit the . and () for these functions, e.g. myObj.operation(arg) becomes myObj operation arg.

Every infix function needs exactly 2 parameters — the one on the left and the one on the right. For this reason, infix functions are always defined as methods on some class (or extension functions, but we’ll talk about those later). The class represents the argument on the left. For a method to be declared infix, it must have exactly one parameter, which represents the argument on the right.


//sampleStart
class MyList<T> : ArrayList<T>() {
    infix fun concat(other: Collection<T>): MyList<T> {
        val result = MyList<T>()
        result.addAll(this)
        result.addAll(other)
        return result
    }
    companion object {
        fun <T> from(vararg elements: T): MyList<T> {
            val result = MyList<T>()
            result.addAll(elements)
            return result
        }
    }
}

// Syntactic sugar for MyList.from(1, 2, 3).concat(listOf(4, 5, 6))
val result = MyList.from(1, 2, 3) concat listOf(4, 5, 6)
//sampleEnd
fun main() {
    val poem = """
        In the coding harmony, Kotlin's the chord,
        With extension functions, it's never ignored.
        From notes to melodies, a musical spree,
        In the world of programming, it's the key!
    """.trimIndent()
    println(poem)
}

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

The Kotlin Primer