...

/

Validating Input and Preferring Sealed Classes over Enums

Validating Input and Preferring Sealed Classes over Enums

Learn how to do input validation in Kotlin and why we prefer sealed classes over enums.

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() ...