why data receiver maxByOrNull of class requires validation of not being null?

365 views Asked by At

I'm new to kotlin and I have a question.

Well, here is the code:

   data class People(val name: String?=null, val age: Int?=null )

   fun main(){
       
   val people = listOf(People("Alice"),People("John",32))
   val older = people.maxByOrNull{ it.age ?: 0 }
   
   // val resultadoFinal = maisVelho
   println("${older?.name}")
    
   println("${people[0].name}")
}

if in println("${older?.name}") you take out the '?', you'll get this error:

Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type People?

What I understoon is this means that there is a possibility that what maxByOrNull returns might be null, so you have to validate it as not being null. My question is: Is that correct?

Also, reading about the maxByOrNull in https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/max-by-or-null.html

There is this part:

val emptyList = emptyList<Pair<String, Int>>()
val emptyMax = emptyList.maxByOrNull { it.second }
println(emptyMax) // null

this part emptyList<Pair<String, Int>>() is very strange for me. What is that? I know he is creating an empty list, but what is this language? Will I learn this further? this Pair thing, why he puts String and Int inside it? Isn't there a simpler way to create an empty list in kotlin?

Well, that is it. Thanks.

1

There are 1 answers

0
CFrei On

In short, yes, correct what you think about maxByOrNull. If the list itself is empty, you do not get back any element.

the emptyList function is just a convenience function to create a (typed) empty list containing 0 elements of type Pair<String,Int> (see Kotlin docs for emptyList).

Instead of an empty list one could have used val emptyList = null, but forces you to check for null, before you execute maxByOrNull: val emptyMax = emptyList?.maxByOrNull { it.second }.