I avoid using the not-null !!
operator because it reduces confidence that the code won't crash at runtime. And I also avoid list operations that can cause a crash if the list is empty, such as maxBy
(as opposed to maxByOrNull
). But sometimes avoiding both of these at the same time feels impossible. Here's an example:
data class Person(val name: String, val age: Int, val height: Int)
val people: List<Person> = // Initialize a list of people
println("Tallest person for each age:")
people.groupBy{it.age}.forEach{ age, peopleWithThisAge ->
val tallestPersonForThisAge = peopleWithThisAge.maxByOrNull { it.height }!!
println("$age: ${tallestPersonForThisAge.name}")
}
I know that peopleWithThisAge
will never be empty because groupBy
only creates lists with at least one value. But the complier doesn't know that. Is there an elegant way to handle this situation?
Even when I, as a human reading the code, know that the code won't crash, I want to avoid the mental burden of someone else having to read a bunch of code to understand that. If I wanted that mental burden, I would still be programming in Java.