How to return a new instance of `T` in an inline reified function?

599 Views Asked by At

I have the following code:

private inline fun <reified T : Number> T.test(): T {
    if (T::class.java == Double::class.java) {
        return 0.0
    }

    return this
}

I expected that that would work (as long as I checked the type of T), but the IDE points this out:

The floating-point literal does not conform to the expected type T

enter image description here

Is there any way to make it work?

1

There are 1 best solutions below

2
Tenfour04 On BEST ANSWER

You have to cast it to T since the compiler isn't sophisticated enough to figure it out.

private inline fun <reified T : Number> T.test(): T {
    if (T::class == Double::class) {
        return 0.0 as T
    }

    return this
}