使用“大于",“小于"的正确方法是什么? Kotlin中可空整数的比较? [英] What is the right way of using "greater than", "less than" comparison on nullable integers in Kotlin?
本文介绍了使用“大于",“小于"的正确方法是什么? Kotlin中可空整数的比较?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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?
推荐答案
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
因此,如果您尝试获取年龄或在实际分配年龄之前检查isAdult,则会获得异常而不是null.
So if you try to get age or check isAdult before age was actually assigned then you'll get exception instead of null.
无论如何,我认为年龄= 0是某种魔术,有一天可能会导致问题(甚至是产品问题).
Anyway I believe age = 0 is some kind magic that one day may lead to issue (even prod issue).
这篇关于使用“大于",“小于"的正确方法是什么? Kotlin中可空整数的比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文