Search⌘ K
AI Features

Validating Input and Preferring Sealed Classes over Enums

Explore how to use Kotlin's require and check functions for clearer input validation and state checks. Understand why sealed classes are preferred over enums for representing states with associated data, improving code readability and robustness.

We'll cover the following...

Input validation is a necessary but very tedious task. How many times did we have to write code like the following?

fun setCapacity(cap: Int) {
if (cap < 0) {
throw IllegalArgumentException()
}
...
}
A function that sets a capacity and throws an exception if the argument is negative

Instead, we can check arguments with the require() function:

fun setCapacity(cap: Int) {
require(cap > 0)
}
A function that sets a positive capacity using the require function

This makes the code a lot more fluent. We can use require() to check for nulls:

fun printNameLength(p: Profile) {
require(p.firstName != null)
}
A function that prints the length of a profile's first name using the require() function

But there’s also requireNotNull() for that:

fun printNameLength(p: Profile) {
requireNotNull(p.firstName)
}
Using the requireNotNull() function

Use ...