6

How to use less than (<) or greater than (>) operator in kotlin?

I have checked comparedTo(other: Int?) function, but it only returns Int?.

class Adapter{ private var mNewsCategories: List<NewsCategory>? = null //...... val isAnything= this.mNewsCategories?.size?.compareTo(0)) //...... } 

The val isAnything returns another Int?. Actually, I need a Boolean variable.

Thanks in advance

6
  • Why don't you just use < 0 or > 0? Commented Feb 18, 2018 at 11:29
  • 1
    @OliverCharlesworth what would null < 0 evaluate to? Commented Feb 18, 2018 at 11:54
  • see this stackoverflow.com/q/29223898/9130109 Commented Feb 18, 2018 at 11:54
  • @MarkoTopolnik - What does the OP want it to evaluate to? Commented Feb 18, 2018 at 12:00
  • @OliverCharlesworth Don't know, but I wonder how adding > 0 would work semantically with null values, since that's how I understood your suggestion. Commented Feb 18, 2018 at 12:11

1 Answer 1

9

It’s not possible to use > on nullable types. If you consider null to map to the size 0, i.e. empty size, you can do:

val isAnything = (this.mNewsCategories?.size? ?: 0) > 0 

While this will fix your problem, you should consider using isNotEmpty instead:

val isAnything = this.mNewsCategories?.isNotEmpty() ?: false 

The Elvis Operator is explained here.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the precious answer. Can you explain elvis operator do, it will help lot of others .
Though, when checking for empty lists using isNotEmpty is probably easier than comparing to 0
That's probably true

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.