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

前端 未结 6 1725
南方客
南方客 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:37

    A generic and flexible solution would be:

    infix fun > T?.isGreaterThan(other: T?): Boolean? =
        if (this != null && other != null) this > other else null
    
    infix fun > T?.isGreaterThanOrEqual(other: T?): Boolean? =
        if (this != null && other != null) this >= other else null
    
    infix fun > T?.isLessThan(other: T?): Boolean? =
        if (this != null && other != null) this < other else null
    
    infix fun > T?.isLessThanOrEqual(other: T?): Boolean? =
        if (this != null && other != null) this <= other else null
    
    

    Depending on your needs, you could use it as:

    public var isAdult: Boolean? = false
        get() = _age isGreaterThanOrEqual 18
    

    or:

    public var isAdult: Boolean = false
        get() = _age isGreaterThanOrEqual 18 == true
    

提交回复
热议问题