可空浮点数错误和不可空浮点数错误之间的 Kotlin 乘法,即使有空检查

Kotlin multiplication between nullable and non-nullable float errors even with null check

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

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
}

这些属性可以为 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 不允许我 select 并复制消息):

我也尝试用这段代码在 Kotlin playground 中复制它:

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。据我所知,这两个代码示例几乎相同。

我究竟做错了什么,我该如何解决?

// 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