Validating input
Input validation is a crucial aspect of programming, ensuring that functions receive appropriate and expected inputs. Kotlin offers several built-in functions to streamline this process, making the code more concise and expressive.
The require()
function is used for argument validation. It throws an IllegalArgumentException
if its condition is not met. This simplifies the traditional way of argument checking:
fun setCapacity(cap: Int) {
require(cap > 0)
}
This is more fluent compared to manually throwing an exception:
fun setCapacity(cap: Int) {
if (cap < 0) {
throw IllegalArgumentException("Capacity must be positive")
}
...
}
The requireNotNull()
function is specifically designed for null checks:
fun printNameLength(p: UserProfile) {
requireNotNull(p.firstName) { "First name must not be null " }
requireNotNull(p.lastName)
println(p.firstName.length + 1 + p.lastName.length)
}
...