Operator!


#1

In the documentation for function literals they have this code in section Function Types:

fun max<T>(collection : Collection<out T>, less : (T, T) -> Boolean) : T? {
  var max : T? = null
  for (it in collection)
  if (max == null || less(max!!, it))
  max = it
  return max
}
My question is what the  !! operator is used for?

#2

Hello Kotlinsky,

the !! operator asserts that a value is NOT NULL at the time it is called, otherwise a NPE is thrown. This is similar to the Elvis operator (?.), but the Elvis operator returns null instead of throwing an exception. In the code sample you provided, max is already checked for nullity (max == null), therefore, you can access the value with !! in the knowledge that a NPE can’t ever be thrown.

I think this represents a certain immaturity of the Kotlin compiler. After you check (max == null), there should be no need to use !! to access it safely, but the compiler isn’t able to determine that. Maybe in a future version :slight_smile:


#3

Thanks. I had a feeling I should have checked the documentation a little more thoroughly.