Advanced Functions

Advanced Functions in Kotlin: --- A booking office at a busy railway terminus keeps a fare table behind the brass grille -- a bound ledger listing every…


The Analogy: The Booking Clerk and the Fare Table

A booking office at a busy railway terminus keeps a fare table behind the brass grille -- a bound ledger listing every destination, every class of travel and every surcharge. When a traveller steps up and says "third-class single to York," the clerk looks up the destination, reads the column, stamps one ticket and calls one fare. That is the ordinary function: one name, one argument, one result.

But the office handles more than singles. A school party arrives: thirty children, one destination, one class. The clerk does not write thirty separate tickets by thirty separate lookups. He accepts the whole group as one transaction, iterates through the headcount internally and stamps one group ticket. The party is a variable-argument parameter -- any number of travellers fed to the same fare lookup. If a second party of six arrives a moment later, the clerk can splice the two lists together with a single hand gesture and process all thirty-six under one call. That splice is the spread operator: an existing batch unpacked into a slot that expects individual items.

Between themselves the clerks use a shorthand. Instead of saying "issue one return ticket from here to Edinburgh at the standard fare," a senior clerk says "Edinburgh return." That two-word phrase -- destination then ticket type -- is an infix call: a binary operation written between its operands with no parentheses and no verb. The convention works only because exactly two pieces of information are needed and both parties have agreed on the order. A three-argument instruction cannot be shortened this way and the office rules forbid it.

Some fare calculations require an intermediate step. A clerk computes a branch-line surcharge on a scrap of paper, adds it to the trunk fare and throws the scrap away. That scratch calculation is a local function: it exists only inside the trunk-fare routine and no one outside the window can see it. The failure mode is the clerk who, instead of computing the surcharge once on paper, writes it on a docket, hands the docket to himself, reads the docket, writes a new docket, and so on until the stack of dockets buries the counter. The booking office solved this decades ago: the surcharge table has a line at the bottom that says "if the branch has its own branch, return to the top of this table with the new branch" so that only one sheet of paper is ever in use. That return-to-top instruction is the tailrec annotation.


Syntax or Core Structure

fun sumFares(vararg pence: Int): Int {
    var total = 0
    for (p in pence) total += p
    return total
}

infix fun Int.shillings(pence: Int): Int = this * 12 + pence

tailrec fun gcd(a: Int, b: Int): Int =
    if (b == 0) a else gcd(b, a % b)

fun main() {
    val group = sumFares(45, 60, 45, 90, 60)
    println("group fare: " + group + " pence")

    val extras = intArrayOf(30, 55)
    val combined = sumFares(45, *extras, 90)
    println("combined: " + combined + " pence")

    val fare = 3 shillings 6
    println("3s 6d = " + fare + " pence")

    fun branchSurcharge(miles: Int): Int = miles / 10
    val trunk = 200 * 2
    val branch = trunk + branchSurcharge(200)
    println("trunk: " + trunk + "  branch: " + branch)

    println("gcd(48, 18) = " + gcd(48, 18))

    val op: (Int, Int) -> Int = ::gcd
    println("via ref: " + op(48, 18))
}

The five features appear one after another. sumFares takes vararg pence: Int, so the caller can pass any number of Int values separated by commas. The spread operator *extras unpacks an existing IntArray into that slot, and Kotlin allows mixing individual values with spreads in the same call. The infix modifier on shillings lets the caller write 3 shillings 6 instead of 3.shillings(6). The local branchSurcharge lives inside main and captures nothing from the enclosing scope here, but it could. The tailrec on gcd instructs the compiler to rewrite the recursion as a loop -- the annotation is a compile-time contract, not a request, and the build fails if the call is not in tail position. Finally ::gcd produces a first-class function reference stored in a variable whose type is (Int, Int) -> Int.

Output:

group fare: 300 pence
combined: 220 pence
3s 6d = 42 pence
trunk: 400  branch: 420
gcd(48, 18) = 6
via ref: 6

Technical Depth: Varargs, Tail Calls and First-Class References

One vararg per function, and the spread that feeds it

A function may declare at most one vararg parameter. Inside the function that parameter is an Array (or the primitive-specialised IntArray, DoubleArray and so on when the element type is a primitive), so it has a size and can be iterated. Passing an existing array where individual arguments are expected requires the spread operator *, which is not a general dereference -- it is legal only at a vararg call site.

The table below fixes the rules that trip people up. Each entry names a construct, states where it is legal, and states what the compiler actually does with it.

ConstructWhere it is legalWhat the compiler does
vararg xs: Intat most one per functionbinds the loose arguments into an IntArray
spread *arronly at a vararg call sitecopies the array elements into the argument list
infix funmember or extension, exactly one parameterrewrites a op b as a.op(b)
tailrecself-call must be the final actionrewrites the recursion as a loop
::name referenceany function or constructorproduces a value of a function type

The spread copies. When you write sumFares(45, *extras, 90) the runtime builds a fresh array holding 45, the two elements of extras, and 90; the original extras is untouched and unshared. This matters when the vararg element type is a reference type and the callee mutates the array: it mutates the copy.

fun tag(prefix: String, vararg parts: String): String =
    prefix + ":" + parts.joinToString("-")

fun main() {
    val middle = arrayOf("branch", "line")
    println(tag("route", "trunk", *middle, "spur"))
    println(tag("empty"))
    println("part count: " + arrayOf("trunk", *middle, "spur").size)
}

Output:

route:trunk-branch-line-spur
empty:
part count: 4

The second call passes no variadic arguments at all, so parts is an empty array and joinToString yields the empty string. The third line shows that a spread inside an arrayOf literal is also legal and expands in place, giving four elements.

The tail-call rewrite, and where it silently does not apply

tailrec is a promise the compiler checks. The recursive call must be the very last thing the function does on that branch -- not wrapped in an arithmetic expression, not inside a try, not one of two operands still to be combined. When the promise holds, the compiler emits a loop with no new stack frame per call, so the recursion runs in constant stack space. When it does not hold, the build fails with a warning that the call is not in a tail position, which is far better than the silent stack overflow you would get from an unannotated version.

tailrec fun countDown(n: Int, acc: List<Int>): List<Int> =
    if (n == 0) acc else countDown(n - 1, acc + n)

fun sumTo(n: Int): Long {
    tailrec fun go(k: Int, running: Long): Long =
        if (k == 0) running else go(k - 1, running + k)
    return go(n, 0L)
}

fun main() {
    println(countDown(5, emptyList()))
    println("sum to 100 = " + sumTo(100))
    println("sum to 1000000 = " + sumTo(1_000_000))
}

Output:

[5, 4, 3, 2, 1]
sum to 100 = 5050
sum to 1000000 = 500000500000

The accumulator carries the growing result forward as an argument, which is what puts the self-call in tail position. sumTo(1_000_000) would blow the stack under naive recursion; here it runs as a loop and returns 500000500000 without incident. Note that go is a local tailrec function -- the annotation works on nested functions too.

Function references point, they do not copy behaviour

::gcd is a value. It can be stored, passed and returned like any other. A bound reference instance::method captures the receiver; an unbound reference Type::method takes the receiver as its first parameter. Constructor references ::ClassName build instances. All of them have function types and interoperate with the standard-library higher-order functions.

fun main() {
    val words = listOf("york", "leeds", "hull")
    val lengths = words.map(String::length)
    println("lengths: " + lengths)

    val upper: (String) -> String = String::uppercase
    println("upper: " + words.map(upper))

    val builders = listOf(::StringBuilder)
    val sb = builders[0]("start")
    println("built: " + sb.append("-end"))
}

Output:

lengths: [4, 5, 4]
upper: [YORK, LEEDS, HULL]
built: start-end

String::length is an unbound reference of type (String) -> Int; map feeds each word as the receiver. ::StringBuilder is a constructor reference; calling it builds a new StringBuilder.


Real World Example: The Group Booking Board

The booking office prices group travel to five destinations. Each party pays the full unit fare for its first three travellers and a discounted rate for every traveller beyond the third -- the office's standing rule for parties larger than THRESHOLD. The program below reads a timetable string, prices each party, and prints a padded board with a totals line and a short audit. It uses a vararg to total the party sizes, a local tailrec helper to sum them, a top-level tailrec gcd, and a function reference to invoke it.

const val THRESHOLD = 3
const val DESTS = "York:520:5,Leeds:380:2,Hull:460:4,Whitby:480:3,Scarborough:300:6"
const val W_DEST = 12
const val W_PARTY = 6
const val W_UNIT = 6
const val W_FULL = 7
const val W_FARE = 7
const val W_SAVED = 6

fun groupFare(unit: Int, party: Int): Int {
    val discounted = unit - unit / 10
    return unit * minOf(party, THRESHOLD) + discounted * maxOf(0, party - THRESHOLD)
}

fun sumParty(vararg counts: Int): Int {
    tailrec fun go(i: Int, acc: Int): Int =
        if (i == counts.size) acc else go(i + 1, acc + counts[i])
    return go(0, 0)
}

tailrec fun gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)

fun row(dest: String, party: String, unit: String,
        full: String, fare: String, saved: String): String =
    dest.padStart(W_DEST) + party.padStart(W_PARTY) + unit.padStart(W_UNIT) +
        full.padStart(W_FULL) + fare.padStart(W_FARE) + saved.padStart(W_SAVED)

fun main() {
    val entries = DESTS.split(",").map { it.split(":") }
    val ruleWidth = W_DEST + W_PARTY + W_UNIT + W_FULL + W_FARE + W_SAVED
    println(row("DESTINATION", "PARTY", "UNIT", "FULL", "FARE", "SAVED"))
    println("-".repeat(ruleWidth))

    var tFull = 0
    var tFare = 0
    var tSaved = 0
    val parties = mutableListOf<Int>()
    var bestName = ""
    var bestSaved = -1
    for (e in entries) {
        val name = e[0]
        val unit = e[1].toInt()
        val party = e[2].toInt()
        val full = unit * party
        val fare = groupFare(unit, party)
        val saved = full - fare
        tFull += full; tFare += fare; tSaved += saved
        parties.add(party)
        if (saved > bestSaved) { bestSaved = saved; bestName = name }
        println(row(name, party.toString(), unit.toString(),
            full.toString(), fare.toString(), saved.toString()))
    }
    println("-".repeat(ruleWidth))
    val totalParty = sumParty(*parties.toIntArray())
    println(row("TOTALS", totalParty.toString(), "--",
        tFull.toString(), tFare.toString(), tSaved.toString()))

    println("passengers via vararg: " + totalParty)
    println("full " + tFull + " = fare " + tFare + " + saved " + tSaved +
        " agree: " + (tFull == tFare + tSaved))
    val g: (Int, Int) -> Int = ::gcd
    println("gcd of " + entries[0][1] + " and " + entries[1][1] +
        " = " + g(entries[0][1].toInt(), entries[1][1].toInt()))
    println("biggest saver: " + bestName + " at " + bestSaved)
}

Output:

 DESTINATION PARTY  UNIT   FULL   FARE SAVED
--------------------------------------------
        York     5   520   2600   2496   104
       Leeds     2   380    760    760     0
        Hull     4   460   1840   1794    46
      Whitby     3   480   1440   1440     0
 Scarborough     6   300   1800   1710    90
--------------------------------------------
      TOTALS    20    --   8440   8200   240
passengers via vararg: 20
full 8440 = fare 8200 + saved 240 agree: true
gcd of 520 and 380 = 20
biggest saver: York at 104

Trace one row. York sends five travellers at 520 pence each. Three pay the full 520 and two pay the discounted rate of 520 - 520 / 10, which is 520 - 52, or 468. The party fare is 520 * 3 + 468 * 2, that is 1560 + 936, giving 2496 against a full price of 2600 and a saving of 104. Leeds and Whitby have parties of two and three, at or below the threshold, so no one is discounted and their SAVED column is zero.

The four features each earn their place. sumParty is variadic, called as sumParty(*parties.toIntArray()) with the accumulated party list spread into it, and its inner go is a local tailrec function summing the counts as a loop. The top-level gcd is tailrec too, and it is invoked through the reference g, whose type is (Int, Int) -> Int; the greatest common divisor of the first two unit fares, 520 and 380, is 20. The row helper takes six pre-stringified columns and pads each to a named width, so the board is exactly 44 characters wide on every line.

The two audit lines look reassuring and prove almost nothing. saved is defined as full - fare, and tSaved is the running sum of those differences, so full = fare + saved reduces to tFull == tFare + (tFull - tFare) -- an identity that would print agree: true even if groupFare returned nonsense. The check is real only for the accumulation, not for the pricing rule it appears to bless.

The genuine design flaw is quieter and lives in groupFare. The discounted rate is unit - unit / 10, and unit / 10 is integer division that truncates toward zero. For every unit fare in this timetable the division is exact -- 520, 380, 460, 480 and 300 are all multiples of ten -- so the board shows a clean ten-percent reduction. Feed it a fare of 525 and the discount becomes 525 / 10, which is 52, not 52.5, so the traveller is charged 473 rather than 472.5 and the office silently keeps the half-penny on every discounted head. The rounding bias is directional, always in the office's favour, and it is invisible here only because the sample data was chosen to divide evenly. A narrower limit: padStart never truncates, so the first destination longer than eleven characters would push its whole row past 44 and misalign the board.


Common Mistakes

  1. Passing an array to a vararg without the spread operator. Writing sumFares(extras) where extras is an IntArray does not compile, because a single array is not the same as several loose Int arguments. You must write sumFares(*extras) so the elements are unpacked into the argument list. The mistake is easy to make because the array feels like the right shape.
  1. Expecting a spread to alias the original array. The spread copies the elements into a fresh backing array for the call. If the callee mutates its vararg parameter, the caller's array is unaffected. People who rely on shared mutation are surprised when their changes vanish at the return.
  1. Annotating a non-tail call with tailrec and ignoring the warning. return n * factorial(n - 1) is not in tail position -- the multiplication happens after the call returns -- so the compiler refuses to optimise it and warns. Treating the warning as noise leaves you with ordinary recursion and a stack overflow on large inputs, exactly the outcome the annotation was meant to prevent.
  1. Declaring more than one vararg per function. Only one variadic parameter is allowed, because the compiler cannot tell where one variadic run ends and the next begins. A second vararg is a compile error, not a runtime surprise.
  1. Making an infix function take anything other than one parameter. Infix notation is defined for a single-argument member or extension. A zero- or two-parameter function cannot be infix, and forgetting this produces a confusing error at the declaration rather than the call.
  1. Mixing infix calls with other operators and expecting arithmetic precedence. Infix functions all share one precedence level, lower than the named arithmetic operators but higher than the comparison operators. 1 shl 2 + 3 is not (1 shl 2) + 3; the + binds tighter, giving 1 shl 5. When in doubt, parenthesise.
  1. Believing a local function is free of capture cost. A local function that closes over a mutable variable of the enclosing scope forces that variable onto the heap in a wrapper, so it is not always the zero-overhead construct people assume. Pure local functions that capture nothing are cheap; capturing ones are not.
  1. Confusing a bound and an unbound method reference. String::length is unbound and has type (String) -> Int; someString::length is bound and has type () -> Int. Passing the wrong one to a higher-order function gives an arity mismatch that the error message describes in terms of parameter counts, which can be baffling until you see which form you wrote.
  1. Assuming vararg and a List parameter are interchangeable. They are not the same type. A function taking vararg xs: Int cannot be handed a List<Int> directly, and one taking List<Int> cannot be called with loose arguments. Converting costs a copy in either direction, so choose the parameter shape that matches how callers actually hold their data.

Best Practices

  • Prefer a List parameter over vararg when callers usually already hold a collection; reserve vararg for the case where loose literal arguments are the common call shape.
  • Put the vararg parameter last, or give every parameter after it a name at the call site, so the compiler can tell the variadic run from the trailing arguments.
  • Reach for tailrec whenever a recursive function can carry its result in an accumulator, and treat the compiler's tail-position warning as a hard error to fix, never as noise to suppress.
  • Restructure a non-tail recursion into a tail-recursive helper with an accumulator rather than raising the JVM stack size; the accumulator form is both safe and usually clearer.
  • Use infix only for genuinely symmetric or operator-like binary relationships where a op b reads better than a.op(b); do not make an ordinary one-argument method infix just because you can.
  • Parenthesise any expression that mixes an infix call with arithmetic or bitwise operators, because the single shared precedence of infix functions rarely matches a reader's intuition.
  • Reach for method and constructor references over trivial lambdas: map(String::length) states intent more directly than map { it.length } and avoids naming a parameter you never wanted.
  • Keep a local function local. If a nested helper starts being useful elsewhere, promote it to a top-level or member function rather than duplicating it, but do not promote prematurely -- a helper used in one place is clearest where it is used.

Practice Exercises

  1. Write a function joinPaths(vararg segments: String): String that joins its segments with a single / between each, collapsing any accidental empty segments. Call it once with loose string literals and once by spreading an existing array, and verify both produce the same result.
  1. Implement power(base: Int, exp: Int): Long as a tailrec function using an accumulator. Confirm that the compiler accepts the tailrec annotation, then deliberately rewrite it into a non-tail form and record the exact warning the compiler emits.
  1. Define an infix extension infix fun Int.upTo(end: Int): List<Int> that returns the inclusive list of integers from the receiver to end, or an empty list when the receiver exceeds end. Show that 3 upTo 6 and 6 upTo 3 behave as specified, and explain why upTo cannot take a second parameter.
  1. Given fun apply2(f: (Int) -> Int, x: Int): Int = f(f(x)), call it three ways for the same doubling behaviour: with a lambda, with a local function reference, and with a bound method reference on an object you define. Verify all three return the same value for a chosen input.