var _age: Int? = 0
public var isAdult: Boolean? = false
get() = _age?.compareTo(18) >= 0
Run Code Online (Sandbox Code Playgroud)
这仍然给我一个null安全的编译错误,但是如何在这个问题上使用>,<,> =或<=?
Ser*_*kov 22
var age : Int? = 0
public val isAdult : Boolean?
get() = age?.let { it >= 18 }
Run Code Online (Sandbox Code Playgroud)
另一个解决方案是使用代表:
var age : Int by Delegates.notNull()
public val isAdult : Boolean
get () = age >= 18
Run Code Online (Sandbox Code Playgroud)
因此,如果您尝试在年龄实际分配之前获得年龄或检查isAdult,那么您将获得异常而不是null
无论如何,我认为年龄= 0是某种神奇,有一天可能导致问题(甚至刺激问题)
Kotlin 肯定可以Int为此使用扩展函数,但直到他们这样做:
fun Int?.isGreaterThan(other: Int?) =
this != null && other != null && this > other
fun Int?.isLessThan(other: Int?) =
this != null && other != null && this < other
Run Code Online (Sandbox Code Playgroud)
我的方法返回false,而不是null如果任一操作数是null。这对我来说更有意义。
| 归档时间: |
|
| 查看次数: |
8126 次 |
| 最近记录: |