is it idiomatic to just not use `UInt`? typically ...
# getting-started
y
is it idiomatic to just not use
UInt
? typically in a strongly-typed language you would use an unsigned type for validation, but everything ever takes
Int
(for "Java reasons" which I do understand) so there's going to be conversions at the call site everywhere.
y
Do remember that UInt gives you double the range for positive numbers too, which is nice. Eveyrthing takes an
Int
, sure, but you can always write wrappers around them if you know that they can handle `UInt`s too
y
but then again, if everything takes
Int
, then the fact that
UInt
is wider is not helpful since it's going to fail the cast at the call site.
in fact, thinking about it again, it's worse than "not helpful", you can store a whole bunch of values that you can't actually use in functions that take
Int
k
Can you give examples of cases where things would break? My thoughts are: 1. A function that takes only positive integers usually has a range of valid values, and that range is not necessarily
Int.MAX_VALUE
, but something a lot smaller (such as a fixed number of digits). In that case, you would have to check the range anyway, irrespective of whether it's a
UInt
or an
Int
. 2. Casting from
UInt
using
toInt()
is a no-op in bytecode. 3. Java functions that take unsigned integers as
int
are usually fine with a
UInt
represented as a negative
int
. For example, Protobuf function
UInt32Value.of(int)
will create a large positive number from a negative
int
. Therefore you can do
val x: UInt = ...; val y = UInt32Value.of(x.toInt())
👍 1
y
@Klitos Kyriacou that helps! 2 + 3 together satisfies me regarding internal representation. regarding 1, I'm not completely convinced, but it just moves to the magnitude check to the call site, which isn't too bad.
it means that a function that operates on `UInt`s larger than
Int.MAX_VALUE
needs to be rethought, but again, it's manageable. on par with other Java interop quirks
k
Remember, however, that unsigned types are a recent addition to Kotlin, so if you need to support older code, you may need to stick to the JVM-standard ones.
thank you color 1