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

前端 未结 6 1706
南方客
南方客 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条回答
  •  Happy的楠姐
    2021-01-03 19:47

    I used the null coalescing operator to convert from nullable Int? to non-nullable Int:

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

提交回复
热议问题