Hi, I'm trying to make a class generic on all type...
# getting-started
f
Hi, I'm trying to make a class generic on all types that support arithmetic operations. Is that somehow possible?
c
No. There are classes that accept some arithmetic operations but not others.
y
You could make an interface that defines arithmetics for a specific type, then provide implementations for it and a way to choose it based on a reified type. I have a (slightly domain-specific) version of that here, but you can adapt it easily to fit your needs. The code for determining a datatype from a reified type is here. Basically, the code defines an interface
NumberOps<N>
that defines arithmetic on type
N
. N is constrained to
N : Number, N : Comparable<N>
because Number provides (truncating/unsafe) conversions to Int/Float/etc, and Comparable provides comparisons between N values. Those properties could also just be part of the interface instead, which might make it easier to implement for more unusual types (like UInt, which doesn't extend Number). The reason why NumberOps doesn't have
times
and
divides
and instead FloatingPointOps has them is that, in the domain of the library, we only want those operations to work on floating point numbers so that they preserve (up to an epsilon because floating point isn't exact) properties like
1 / 2 * 2 == 1
and so each type that has a
NumberFpOps
has a "carrier" floating point type
FP
that it fits into perfectly, and thus all multiplication and division should happen on that type, before finally converting back to
N
. This is quite domain-specific, and I can imagine that in your code you likely will just want to define all those operations, and so take the code linked above as guidance and not as gospel.
f
Thank you very much for the detailed reply! This gives me lot of pointers to get started, thanks!
y
If you run into any issues don't hesitate to ask!