Generics Question: I want to constrain a type in a...
# announcements
t
Generics Question: I want to constrain a type in a class such that the type supports arithmetic operations, like so:
Copy code
data class Item<T>(val operand1: T, val operand2: T) {
      val result: T = operand1 / operand2
}
But it gives me errors about BigDecimal (I guess this is the first class it tried to match. So I need to constrain T to be only types that support division, like T: Number, T: divideBy or something. Is this possible in Kotlin? Thank you!
a
There is no way to do that sadly. You'd need a common interface that provides methods for the arithemtic operations that
Int
,
Float
etc. implements
but there is none. Your best bet is to use ad-hoc polymorphism:
Copy code
data class Item<T>(val operand1: T, val operand2: T, val operation: (T, T) -> T) {
    val result: T = operation(operand1, operand2)
}
t
Bummer, that is what i suspected. I am currently checking types inside the methods, but it is ugly of course.I guess maybe I would write my own generic divide and extend Int and Double to support it and then use that within the member func. Thanks!
a
kotlin is constrained by java on this one
t
Then maybe when we move to the KVM. 😉 Thanks again!
a
yeah 😂