Why Kotlin doesn't use `UInt` type for `String.len...
# getting-started
j
Why Kotlin doesn't use
UInt
type for
String.length
or
Collection.size
? Is this for JVM compatibility? Is it safe to assume those values will never be negative?
m
I don't know the actual reason, but I assume it would be that most people interact with it as an
Int
. It also predates
UInt
so changing it would be a pretty breaking change.
repeat(list.size - 1 {}
would not compile anymore, one of the numbers would have to get casted. It's better than old languages where mixed type maths were allowed and you end up with the maximum UInt if size was 0. I think it is safe to assume that it will not be negative. But a custom collection could do something very broken.
👍 1
c
Presumably so it doesn't make doing basic arithmetic with those functions a pain.
👍 1
j
But a custom collection could do something very broken.
I did not thought about that, you're right, it could bring some issues. 😬
c
I rarely use UInt even for non negative ints. If I really want to convey type information for my numbers I'm more likely to use a value type.
j
yep, I'm starting to think this could be better
r
There's also the issue of what type
indexOf
would return. If it returns an
Int
, your missing half the collection. If it returns
UInt
, how do you represent not found (which is usually
-1
)? Similar issue for functions like
binarySeach
, which returns
-index - 1
when an element isn't found so you know the insertion point. (Using wrapper values would require instances, which would be terrible when those functions are used in hot loops.)
💯 2
a
https://github.com/Kotlin/KEEP/blob/master/proposals/unsigned-types.md#non-negative-integers
While unsigned integers can only represent positive numbers and zero, it’s not a goal to use them where non-negative integers are required by application domain, for example, as a type of collection size or collection index value.
1
💯 1
j
Really interesting, thank you Alexey!