I do extensions function which will be all numbers with null translates to zero. I did a type cast, added "UNCHECKED_CAST" as the warning went, but the idea that you can somehow make it all easier (that is, I did it all wrong) does not let go.

fun main(args: Array<String>) { var i1: Int? = null var i2: Int = i1.fixNull() print(i2) } @Suppress("UNCHECKED_CAST") fun <T : Number> T?.fixNull(): T { if (this == null) return 0 as T return this } 

    1 answer 1

    That's shorter:

     @Suppress("UNCHECKED_CAST") fun <T : Number> T?.fixNull(): T = this ?: 0 as T 

    And whether it is correct or not depends on the task that it solves.
    Without this, it is difficult to judge.

    • The task is to convert all numeric types (double, float, long, int ...) when calling fixNull () from null to 0 (0.0, 0.0f, 0L, 0 ...), but I do not know all the nuances of kotlin and generics. - GixWay