【问题标题】:Kotlin multiplication between nullable and non-nullable float errors even with null check即使使用空检查,可空和不可空浮点错误之间的 Kotlin 乘法
【发布时间】:2015-12-06 23:42:16
【问题描述】:

我正在从 Java 中移植一个名为 ShapeData 的类,该类填充了可空类型。它看起来像这样:

class ShapeData {
    var type: Shape.Type? = null // Circle, Edge, Polygon, Chain

    // PolygonShape / ChainShape
    var vertices: FloatArray? = null
    var offset: Int? = null
    var len: Int? = null

    // setAsBox
    var hx: Float? = null
    var hy: Float? = null
    var center: Vector2? = null
    var angle: Int? = null

    // CircleShape
    var radius: Float? = null
    var position: Vector2? = null

    // EdgeShape
    var v1: Vector2? = null
    var v2: Vector2? = null
}

这些属性可以为空,因为它们是从 JSON 读取的并且可能不存在,并且由于某些字段允许负值 -1 不是有效的默认值。

如果某些属性存在,则需要对其进行缩放,以便我将以前的静态方法转换为 Kotlin 顶级函数,但是我遇到了一些问题:

fun scaledShapeData(data: ShapeData, scalar: Float): ShapeData {
    return ShapeData().apply {
        type = data.type
        vertices = data.vertices?.map { it * scalar }?.toFloatArray()
        offset = data.offset
        len = data.len
        hx = if(data.hx != null) data.hx * scalar else null // This is marked as an error with "None of the following functions can be called with the arguments supplied" message
    }
}

我得到的确切消息是这样的(图像因为 Android Studio 不允许我选择和复制消息):

我还尝试使用这段代码在 Kotlin 操场上复制它:

fun main(args: Array<String>) {
    var test1 : Float? = 2f
    val test2 : Float = 2f

    var test3 : Float? = if(test1 != null) test1 * test2 else null

    print(test3)
}

这会按预期编译和输出 4.0。据我所知,这两个代码示例几乎相同。

我到底做错了什么,我该如何解决?

【问题讨论】:

    标签: kotlin


    【解决方案1】:
    // This is marked as an error with "None of the following functions can be called with the arguments supplied" message
    hx = if(data.hx != null) data.hx * scalar else null 
    

    您的 Playground 示例与此示例之间的区别在于,data.hx 可能会在null 检查和乘法之间发生变化。

    您可以改用以下内容,在Int 上使用times 函数:

    hx = hdata.hx?.times(scalar)
    

    因为*translated to times

    【讨论】:

      猜你喜欢
      • 2020-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-19
      • 1970-01-01
      • 2018-08-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多