繁体   English   中英

在kotlin中减去2个可为空的浮点类型

[英]Subtract 2 nullable float type in kotlin

我有两个可为空的浮点属性,我想减去它们:

val dis1: Float? = 10.0f
val dis2: Float? = 5.0f

val value = dis1 - dis2

我创建了这个扩展功能。 但它进入无限循环:

operator fun Float?.minus(dis2: Float?): Float {
  return this - dis2
}

简单你可以使用

operator fun Float?.minus(dis2: Float?): Float {
    return (this ?: 0f) - (dis2 ?: 0f)
}

?:检查值是否存在,如果不存在则分配默认值

但它进入无限循环

您的扩展将进入无限循环,因为在返回类型中,您再次在两个可为空的浮点数上调用-(Minus)

除了调用减号运算符之外,您什么都不做,这就是您获得无限循环的方式

进行空检查并调用Float的默认减号运算符

  val dis1: Float? = 10.0f
  val dis2: Float? = 5.0f

  operator fun Float?.minus(dis2: Float?): Float {
        return (this ?: 0f) - (dis2 ?: 0f)

  val value = dis1 - dis2

如果值为null ,您可以只返回 0 以避免KotlinNullPointerException 在你的方法中:

fun minus(value1: Float?, value2: Float): Float{
   val firstValueHelper = value1 :? 0f
   val secondValueHelper = value2 :? 0f

   return firstValueHelper - secondValueHelper
}

如果您想要null - null = 0 ,其他答案很好,但是如果您想要null - null = null那么您需要稍微不同的东西。

如果所需的行为是:

  • 10 - 5 = 5
  • 10 - null = 10
  • null - 5 = -5
  • null - null = null

然后使用以下

operator fun Float?.minus(other: Float?): Float? { 
    return if (this == null && other == null) {
        null
    } else {
        (a ?: 0f) - (b ?: 0f)
    }
}

请注意,可以通过类似的方式实现加法

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM