Fun fact: Unlike Int, UInt doesn't extend Number, but sometimes it does

3 years ago by SillyBanana to c/kotlin

I bumped into this interesting behavior around unsigned types. At first I was confused why UInt doesn't extend Number, but as I was experimenting, it got weirder. It sometimes is a Number (see case c below) and sometimes isn't (see case d)?!

val a: Int = 12
a is Number // true

val b: UInt = 12u
b is Number // doesn't compile, `Incompatible types: Number and UInt`

val c: UInt = 12u
(c as Any) is Number // true, Idea says "No cast needed"

val d: Any = 12u
d is Number // false

I guess this is partly legacy of Java, which doesn't have unsigned types, and partly effect of UInt being value class. I'm curious if someone has a deeper explanation.

daijoubu 2 points 3 years ago

For your example d I'm getting true. At least when using JVM. When switching to Wasm, both c and d result in false.

So it seems that in Kotlin UInt is not a Number, but at runtime on the JVM it is.

path: 0 2820145, hotness: undefined, score: 2, children: 1
xhci 1 point 3 years ago
path: 0 2820145 4138167, hotness: undefined, score: 1, children: 0
kotlin
kotlin

@programming.dev

login for more options
808
109
11

Kotlin is a statically typed programming language for the JVM, Android, JavaScript, and native.

Subreddit rules:

  • Be civil
  • No spam
  • Stay on-topic
  • No fluff

Resources:

go to feed...