Home > Software design >  How to return a new instance of `T` in an inline reified function?
How to return a new instance of `T` in an inline reified function?

Time:01-07

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?

CodePudding user response:

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
}
  •  Tags:  
  • Related