So I made a little number type for a specific soft...
# getting-started
r
So I made a little number type for a specific software and noticed that there is a
Number
super type in Kotlin, which is the super type of numbers like
Int
Float
etc. Should my custom number type (a little Decimal type object that wraps a Long and has some custom rounding rules) also inherit from
Number
? What are the pros and cons? Would there be any gnarly surprises later? If I remember correctly, Java does not have a
Number
super type, so what were the reasons for adding it to Kotlin? What does it do for Kotlin?
d
Java does have Number as a superclass for
Integer
,
Long
,
Double
and other number types That's the main reason to have it in Kotlin
r
Oh, interesting, I did not notice that before. Thanks for pointing it out! So, Java does not have sealed classes (I think?), so was Java’s Number meant ONLY for the standard number types, or were you also meant to extend it? Would it even make any practical difference if my number type extended from Number?
d
> Java does not have sealed classes It does starting from Java 15 IIRC > or were you also meant to extend it?
Number
is an arbitrary abstract class, you can extend it > Would it even make any practical difference if my number type extended from Number? Well, it will allow you to use your numbers in some abstract APIs which can work with
java.lang.Number
. Do you need it or not depends on which libraries/frameworks you use
d
If you look at what the
Number
class exposes (which I believe is just toInt, toLong, etc...), you can decide whether or not it is useful for your class to extend it. If you find that you're passing instances of your class to a lot of places that take
Number
, and you end up converting it there anyway, then it might make sense to just extend
Number
. If you don't, then maybe not.
k
Also, consider making your class a
@JvmInline value class
if you haven't already.
r
I considered making it a value class. How well does that work for KMP, i.e. JS and Swift?
Ah, looks like value classes are not supported by the Objective-C exporter.