What is the right way of using “greater than”, “less than” comparison on nullable integers in Kotlin?

前端 未结 6 1703
南方客
南方客 2021-01-03 19:00
var _age: Int? = 0

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

This still gives me a null-safety, compile error,

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-03 19:55

    You could possibly use the built-in function compareValue:

    fun > compareValues(a: T?, b: T?): Int
    
    public var isAdult: Boolean = false
       get() = compareValues(_age, 18) >= 0
    

    or

    public var isAdult: Boolean = false
       get() = compareValues(18, _age) <= 0
    

    Note however that null is considered less than any value, which may suit your case, but may lead to undesired behavior in other cases. E.g., think of var grantMinorsDiscount.

提交回复
热议问题