mardi 16 avril 2019

How to make a if-else condition in Kotlin using an Integer

I need to compare Objects with a lot of properties in Kotlin to determine if they are equals, and I want to know if I can do it in a non verbose way. (Cast Int -> Boolean) for example.

I have implemented this with When and another operators but I don't find how to cast Integer to Boolean in a Kotlin correct way and make the code cleaner.

In Groovy I can make something like this

@Override
int compareTo(Message message) {
 int equalName = this.name <=> message?.name
 return equalName ?: this.type <=> message?.type
}

In Kotlin I have made this, but Integer is not casting to Boolean so I have to put more code to obtain the same result and it get worst with more properties...

override fun compareTo(other: Message): Int {
    return if (this.name.compareTo(other.name) != 0) -1 
       else this.type.compareTo(other.type)
}

My Object is more verbose than that.

Is there a cleaner way to do this, of it's considered correct the actual implementation.

Aucun commentaire:

Enregistrer un commentaire