What is the right way of using “greater than”, “le

2019-02-21 09:23发布

问题:

var _age: Int? = 0

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

This still gives me a null-safety, compile error, but how can I use >, <, >= or <= in this matter?

回答1:

var age : Int? = 0

public val isAdult : Boolean?
    get() = age?.let { it >= 18 }

The other solution would be using delegates:

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

So if you try yo get age or check isAdult before age was actually assigned then you'll get exception instead of null

Anyway I believe age = 0 is some kind magic that one day may lead to issue (even prod issue)



回答2:

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)


标签: kotlin