Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

kotlin generics and operator overloading

I want to do some thing like this

data class TestGen<T: Number>(var x : T, var y : T)

public operator<T:Number> fun Int.plus(p:TestGen<T>) = TestGen(this+p.x,p.y)

so how i can do it? or any other idea to do the same thing? becouse i want to do some thing like this

public operator fun Int.plus(p:TestGen<Float>) = TestGen(this+p.x,p.y)
public operator fun Int.plus(p:TestGen<Double>) = TestGen(this+p.x,p.y)
like image 975
Ahmed hamuda Avatar asked Apr 07 '26 18:04

Ahmed hamuda


1 Answers

First you have a syntax error in your declaration of the extension function. Second, a Number does not automatically define the ability to plus + another number. So that creates an issue with using Number as the generic base type. You'll need to, unfortunately, create all permutations that you wish to make valid for all numeric types.

Breaking it down...

operator <T: Number> fun Int.plus(p:TestGen<T>) = TestGen(this+p.x,p.y)

is invalid syntax. The following is more correct, but still won't compile for the reason of "no plus method exists on class Number":

operator fun <T: Number> Int.plus(p:TestGen<T>) = TestGen(this+p.x,p.y)

So to fix it you really need instead is to drop the generic parameter for the function and be specific about each type you are supporting:

@JvmName("IntPlusTestGenWithInt")
operator  fun Int.plus(p:TestGen<Int>) = TestGen(this+p.x,p.y)
@JvmName("IntPlusTestGenWithLong")
operator  fun Int.plus(p:TestGen<Long>) = TestGen(this+p.x,p.y)
@JvmName("IntPlusTestGenWithDouble")
operator  fun Int.plus(p:TestGen<Double>) = TestGen(this+p.x,p.y)
@JvmName("IntPlusTestGenWithFloat")
operator  fun Int.plus(p:TestGen<Float>) = TestGen(this+p.x,p.y)
// etc

The JvmName annotation is required because you are creating extension methods that only differ by a generic parameter, which the JVM erases. So internally the bytecode generated by Kotlin must differentiate each extension method by name, even if you won't see that from the Kotlin code.

You'll need similar variations of the functions for all types you are adding from and to. And you should consider what you are doing with parts of the numbers that don't make sense anymore, for example, the decimal part of a Double added to an Int.

like image 130
Jayson Minard Avatar answered Apr 11 '26 08:04

Jayson Minard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!