Is there a better way to write the following: ```...
# codereview
t
Is there a better way to write the following:
Copy code
override fun compareTo(other: NamedObject): Int {
   // 5 cases
   // we both have null names, compare by oid
   // my name is null, his is not, i'm greater (1)
   // my name is not null, his is, im less (-1)
   // we both have names, compare them
   //    if names are equal, back to oid
   return when {
      name == null && other.name == null -> oid.compareTo(other.oid)
      name == null && other.name != null -> 1
      name != null && other.name == null -> -1
      else -> when (val nameCompare = name!!.compareTo(other.name!!)) {
         0 -> oid.compareTo(other.oid)
         else -> nameCompare
      }
   }
}
In particular, I was hoping to somehow avoid the !!'s in the middle. I was hoping to somehow invoke the smart pointer thing where it turns green and I don't have to check if it's null after I have previously.
e
Copy code
companion object {
    val comparator =
        compareBy(nullsFirst(naturalOrder()), NamedObject::name)
            .thenBy(NamedObject::oid)
}
override fun compareTo(other: NamedObject): Int =
    comparator.compare(this, other)