0Pricing
Kotlin Academy · Lesson

When to Use Each

Trade-offs.

Two Tools, Different Jobs

Infix functions are about readability; tailrec functions are about safe, efficient recursion. They solve unrelated problems.

infix fun Int.add(o: Int) = this + o

tailrec fun sum(n: Int, acc: Int = 0): Int =
    if (n == 0) acc else sum(n - 1, acc + n)

fun main() {
    println(2 add 3)
    println(sum(10))
}

Choose Infix for Fluent APIs

Reach for infix when a call reads better without dots and parentheses, especially in DSLs and pair-building.

fun main() {
    val pair = "id" to 100
    println(pair)
}

All lessons in this course

  1. Infix Functions
  2. Building DSL-like APIs
  3. tailrec Functions
  4. When to Use Each
← Back to Kotlin Academy