1. Why vararg needs a contract for empty input
If a regular function accepts two numbers, the “special case” is usually just one: someone passed the wrong number (or the wrong value). With vararg, there’s another dimension: the number of arguments can range from zero to infinity (well, almost). And zero is not a “compile error”; it’s a valid call.
Imagine you are writing a function maxOf(...). In your head, it looks like “find the maximum”. And then suddenly someone calls maxOf()—and there you are as a developer in the kitchen at 3 a.m., asking the kettle: “What maximum of what, exactly?”. The kettle is silent, the compiler is silent, and the program may crash if you reach into xs[0].
That’s why any vararg function (even the nicest and kindest one) has an important API piece: a behavior contract for empty input. Today we’ll learn not to “leave it to chance”, but to design that contract deliberately.
What a function “contract” means
The word “contract” sounds serious, like a lawyer is about to show up and ask you to sign Terms and Conditions. In programming, a contract is simply an agreement: which inputs are valid and what exactly the function promises to return/do.
For vararg, the contract is especially important because “empty input” is a legal input. And if it’s legal, then either:
- the function must handle it correctly and return some result,
- or the function must honestly say: “there is no result”,
- or the function must “crash” immediately and loudly, because it’s a usage error.
And you choose this not based on mood, but based on the meaning of the task.
2. Contract strategies for empty input
In this section it helps not to start with code right away, but first to pin down the behavior options. We’ll use three strategies that come up all the time (and that you’ll choose again and again throughout your developer life, even if you end up writing not games but space rockets—those also have vararg, it’s just called a “telemetry packet”).
Below is a small table so your brain can see the “decision map” immediately:
| Strategy | Idea | What we return on empty input | When it fits |
|---|---|---|---|
| Neutral result | There is a natural “default value” | For example 0, "", “print nothing” | Sum, concatenation, printing |
| Nullable result | The result is undefined, so we honestly return “no value” | null (and the result type is T?) | Max/min, average, “best result” |
| Fail-fast | Empty input is a programmer error; we cannot continue | Throw an exception via require(...) | When arguments are absolutely required for any meaning |
Now let’s go through each strategy calmly with small examples.
Neutral result
The nicest case is when an operation has a neutral element. For example, the sum of an empty set is logically zero: you added nothing—you got 0. That’s not magic; it’s simply convenient math that makes life much easier.
Let’s make a small function for our learning app. Reminder: in the mini project “Guess the Number” we have attempts (numbers the user entered). Sometimes we want to compute their sum—for example, for stats or for a “joking persistence rating”.
fun sumAttempts(vararg attempts: Int): Int {
var sum = 0
for (a in attempts) sum += a
return sum
}
fun main() {
println(sumAttempts(3, 7, 10)) // 20
println(sumAttempts()) // 0
}
Here the contract is obvious and safe: sumAttempts() returns 0, and it doesn’t look like “we just made something up”. It’s the natural outcome.
Important: a neutral result is not always appropriate. If you start returning a neutral result where none exists, you’ll accidentally invent “magic numbers”, and they bite later.
...OrNull
Now let’s take the task “find the maximum”. For empty input, the maximum is undefined. Some people try to do “well, let the maximum of an empty set be 0”. And that sounds harmless right up until real data contains negative numbers. Then “max of empty = 0” starts lying, and you get a bug that’s very hard to notice.
When there is no result, the most honest path in Kotlin is to return null, i.e., make the result type nullable: Int?.
And here a good naming habit helps: the OrNull suffix. It literally tells the reader: “If the result cannot be obtained—we’ll return null”. You’ve already seen this style on strings and numbers, for example toIntOrNull().
Let’s make a function bestAttemptOrNull(...)—“best attempt” (in our case “best” can be the smallest attempt number: the fewer, the better). But to avoid confusion, in the example we’ll simply find the minimum: fewer attempts is better.
fun minAttemptOrNull(vararg attempts: Int): Int? {
if (attempts.size == 0) return null
var min = attempts[0]
for (a in attempts) {
if (a < min) min = a
}
return min
}
fun main() {
println(minAttemptOrNull(5, 3, 9)) // 3
println(minAttemptOrNull()) // null
}
Notice the order: first we check size == 0, and only then we take attempts[0]. This is not “aesthetic”; it is protection against crashing.
Now—how to use this without pain. We can print the result for the user by providing a “display” value via the Elvis ?: (you’ve already seen it in the topics about null):
fun main() {
val best = minAttemptOrNull()
println(best ?: -1) // -1 (conventionally: "no attempts")
}
It’s important to distinguish: -1 here does not mean the function returned -1. The function honestly returned null. And -1 is our decision only for output, because println(null) looks sad and uninformative.
Fail-fast via require(...)
There are situations where empty input is not “no result”, but a function usage error. That is, the problem is not in user data, but in the fact that the programmer called the function incorrectly.
And here the fail-fast strategy is appropriate: “crash immediately, loudly, and with a clear message”. In Kotlin, for this people often use require(...), which throws IllegalArgumentException if the condition is not met. This is a standard pattern: require for argument checks, check for state checks.
Let’s write a strict version of minimum: minAttemptStrict(...). Its idea: “in the app it makes no sense to search for a minimum if there are no attempts—this is a logic error”.
fun minAttemptStrict(vararg attempts: Int): Int {
require(attempts.size > 0) { "minAttemptStrict: at least one argument is required" }
var min = attempts[0]
for (a in attempts) {
if (a < min) min = a
}
return min
}
fun main() {
println(minAttemptStrict(5, 3, 9)) // 3
}
Why do we use require instead of writing if ... throw ... by hand? Because require is a recognizable standard Kotlin style, and the reader immediately understands: “this is a precondition check”.
At the same time, it’s important to understand the philosophy: require is not a way to “handle bad user input”. If a user entered something wrong, you usually don’t want to crash with an exception—you want to ask them to enter it again. But if a programmer called minAttemptStrict() with no arguments—that’s a bug in the code, and it’s better to learn about it as early as possible.
3. How to choose a strategy
Now for a bit of self-irony: flowcharts are often drawn when someone wants to pretend everything is very formal. But in our case it really helps you avoid guessing from scratch every time.
flowchart TD
A["There is a vararg function"] --> B{"Can empty input still make sense?"}
B -->|Yes, there is a neutral result| C["Return a neutral value (for example 0 or '')"]
B -->|Yes, but there is no result| D["Return null and name it ...OrNull"]
B -->|No, it is a usage error| E["require(size > 0) and a clear message"]
And now an important thought: choosing a strategy is part of API design. That is, not “what is easiest to write”, but “what will be easiest and safest to use”.
Why xs[0] is a trap
There is one very common mistake that appears for almost everyone. It looks like this: you write a function, you need an initial max/min, you take xs[0], and then you “will add the check later”. Then you forget, and then someone calls f() and the program crashes.
To avoid falling into this, it helps to keep a simple template in mind:
Handle emptiness first → then use the first element as the starting point.
Here is a neat version of maxOrNull (for variety—maximum):
fun maxScoreOrNull(vararg scores: Int): Int? {
if (scores.size == 0) return null
var max = scores[0]
for (s in scores) {
if (s > max) max = s
}
return max
}
fun main() {
println(maxScoreOrNull(10, 7, 12)) // 12
println(maxScoreOrNull()) // null
}
This code reads like a normal story: “if there are no values—there is no result; otherwise start with the first and look for larger”.
Names as part of the contract
In programming it’s very easy to make something “formally correct” but “humanly unclear”. So let’s separately talk about names.
When you name a function maxOf(...), you kind of promise: “there will always be a maximum”. If inside it returns null on empty input, that’s not a disaster, but the reader will have to dig into the implementation or documentation.
When you name a function maxOfOrNull(...), you warn in advance: “sometimes null—and that’s normal”. This style is very common in the Kotlin ecosystem, and it makes code more readable simply because the contract is visible on the surface of the name.
And if you make a strict version that does not accept empty input, it’s convenient to add a hint of “strictness” to the name: ...Strict, ...Required, ...NonEmpty. Not because it’s “the rule”, but because it saves colleagues (and future you) from surprises.
4. Example from the app: an attempts report
To make it feel like we are evolving one project, let’s build a mini utility that prints an attempts report in “Guess the Number”. Here vararg is convenient because we can quickly pass several numbers right in the call, without thinking about arrays.
The idea: if there are no attempts, we won’t crash—we’ll print “no data”. This is a good example where ...OrNull gives a convenient contract.
fun minAttemptOrNull(vararg attempts: Int): Int? {
if (attempts.size == 0) return null
var min = attempts[0]
for (a in attempts) if (a < min) min = a
return min
}
fun printAttemptsReport(vararg attempts: Int) {
val best = minAttemptOrNull(*attempts)
println("Attempts: ${attempts.size}") // for example: Attempts: 3
println("Best attempt: ${best ?: "no data"}") // for example: Best attempt: 3
}
fun main() {
printAttemptsReport(5, 3, 9)
printAttemptsReport()
}
There is a small but important detail here: we “proxy” attempts as vararg further into minAttemptOrNull, so we use *attempts. We discussed this in the lecture about the spread operator, but now it’s useful to see that even in a “contract” topic it comes up naturally.
5. require: messages that help
require is good not because it “crashes”. NullPointerException crashes too, and it brings about as much joy as an alarm clock that rang an hour early. require is good because you control where to crash and with what message.
The message should answer two questions: what was wrong, and what was expected. In the example:
require(attempts.size > 0) { "minAttemptStrict: at least one argument is required" }
It includes the function name (so you can quickly find the culprit) and a human expectation (“at least one argument is required”). That kind of text is very helpful during debugging.
And one more thing: require throws IllegalArgumentException. It’s useful to remember at least because if you accidentally wrap everything in try/catch (Exception), you can “hide” the real error.
6. Typical mistakes
Mistake #1: the function crashes on xs[0] because you forgot about empty input.
This is a genre classic: you wrote a min/max search, took the first element as the starting point—and everything is fine until someone calls f(). The fix is simple: either do an early return null and use the type T?, or put require(size > 0) before the first indexed access.
Mistake #2: a “magic value” instead of an honest null.
Returning 0 as “the maximum of an empty set” looks convenient, but that convenience is deceptive. If real data can be negative, you’ll get a lie without a single exception—and that’s the nastiest type of bugs. In such tasks it’s better to use ...OrNull and return null, and set a “print value” from the outside via ?:.
Mistake #3: require(...) is used as user input handling.
require is not “ask the user to enter again”; it is “the program cannot proceed”. If the user entered nonsense, you usually want to explain gently and retry input. And require should be left for programmer errors: when the function contract is violated and continuing makes no sense.
Mistake #4: an unclear name hides the contract.
If a function is named as if the result always exists (maxAttempt, bestScore), but on empty input it returns null or crashes—that’s a surprise. The OrNull suffix makes the contract readable. And if empty input is forbidden, it’s good to reflect that in the name (Strict, NonEmpty) and in the require message.
Mistake #5: require without a message, or with a message like "Invalid input".
Formally the code works, but when the error happens, you get useless diagnostics. Write the message so it helps fix the call: what was expected, what was wrong, where to look.
Mistake #6: you forgot that vararg always allows f()—and that is part of the API.
Sometimes a developer “in their head” assumes “this function will always be called with at least one argument”. But Kotlin does not guarantee that: an empty call compiles. So the empty-input contract must be encoded directly in code: a neutral value, null, or require.
GO TO FULL VERSION