I would like to see number types have more interfa...
# language-proposals
b
I would like to see number types have more interfaces that they conform to, to let me reason about them better. For instance, right now I have to have to make separate, specialized versions of classes for each individual number type, like
Int64Size
vs `Int8Size`: https://github.com/BlueHuskyStudios/Blue-Base/commit/5baf26fb495b29bd9ad4a7b1099d76c9f0c1c163 Just about all the code between these classes is identical, but solely because I can only say either “Use a `Long`” or “Use any implementation of `Number`“, I have to slowly go through every native number type and make separate implementations for these. If I could just specify “This is a
Size
implementation based on a native integer”, I could write it once and let generics fill in the blanks. Swift did this with a set of 9 interfaces, and it makes it super easy to let the compiler reason about what I’m getting at: https://developer.apple.com/documentation/swift/swift_standard_library/numbers_and_basic_values/numeric_protocols https://github.com/apple/swift-evolution/blob/master/proposals/0104-improved-integers.md
👍 1
k
Are users allowed to define their own numeric types? If so, how does mixing work in generic code?
b
Yup! Common examples are big integers, 80- and 128-bit binary numbers, etc. What do you mean by mixing? I can give concrete examples if needed
k
If I have a function that takes two parameters of type eg.
FixedSizeInteger
, can I add them together?
b
Since
FixedWidthInteger
is a protocol (interface) in Swift, it has to be used as a generic constraint instead of a raw parameter type. Additionally, its multiplication function requirements,
multipliedFullWidth(by:)
,
multipliedReportingOverflow(by:)
, and
unsafeMultiplied(by:)
all require the right-hand side and return to be of the same type as the receiver. So, in Swift:
Copy code
func exampleMultiply<T: FixedWidthInteger>(lhs: T, rhs: T) -> T {
    return lhs.unsafeMultiply(by: rhs)
}
Perhaps in Kotlin it might look like this:
Copy code
fun <T: FixedWidthInteger> exampleMultiply(lhs: T, rhs: T) = lhs.unsafeMultiply(by = rhs)
k
That makes a lot of sense, thanks for explaining. It'd be cool to see this in Kotlin as well.
👍🏼 2