在Kotlin中使用“大于”,“小于”比较可归零整数的正确方法是什么?

时间:2015-03-24 02:17:52

标签: kotlin

var _age: Int? = 0

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

这仍然给我一个null安全的编译错误,但是如何在这个问题上使用>,<,> =或< =?

6 个答案:

答案 0 :(得分:16)

var age : Int? = 0

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

另一个解决方案是使用代表:

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

因此,如果您尝试在年龄实际分配之前获得年龄或检查isAdult,那么您将获得异常而不是null

无论如何,我认为年龄= 0是某种可能导致问题(即使是刺激问题)的魔力

答案 1 :(得分:1)

我使用null合并运算符从可空的Int转换?到非可空的Int:

var age: Int? = 0

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

答案 2 :(得分: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

如果任一操作数为false,则我的方法返回null,而不返回null。这对我来说更有意义。

答案 3 :(得分:0)

也可以尝试以下方法:

var position = 100

    mArrayList?.let {

                if (it.size > 0 && position >= 0 ) 
                     return true

            }

答案 4 :(得分:0)

您可以使用内置函数compareValue

fun <T : Comparable<*>> compareValues(a: T?, b: T?): Int
public var isAdult: Boolean = false
   get() = compareValues(_age, 18) >= 0

public var isAdult: Boolean = false
   get() = compareValues(18, _age) <= 0

但是请注意, null被认为小于任何值,这可能适合您的情况,但在其他情况下可能会导致不良行为。例如,想到var grantMinorsDiscount

答案 5 :(得分:0)

通用且灵活的解决方案是:

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

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

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

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

根据您的需要,可以将其用作:

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

或:

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