What is the correct way to use a greater than, less than comparison with integers with a zero value in Kotlin?

var _age: Int? = 0 public var isAdult: Boolean? = false get() = _age?.compareTo(18) >= 0 

This still gives me a zero security error compiling, but how can I use>, <,> = or <= in this question?

+22
source share
3 answers
 var age : Int? = 0 public val isAdult : Boolean? get() = age?.let { it >= 18 } 

Another solution would be to use delegates:

 var age : Int by Delegates.notNull() public val isAdult : Boolean get () = age >= 18 

Therefore, if you try to determine age or check isAdult before age is assigned, you will get an exception instead of zero.

In any case, I believe that age = 0 is some kind of magic that one day can lead to problems (even to a problem).

+22
source

I used a null coalescing operator to convert from nullable Int? to a non-empty Int value:

 var age: Int? = 0 public var isAdult: Boolean? = null get() = if(age == null) null else (age ?: 0 >= 18) 
+1
source

Kotlin can use the extension function in Int for this, but so far they will not:

 fun Int?.isGreaterThan(other: Int?) = this != null && other != null && this > other fun Int?.isLessThan(other: Int?) = this != null && other != null && this < other 

My methods return false , not null if any of the operands is null . That makes more sense to me.

0
source

Source: https://habr.com/ru/post/984165/


All Articles