Hi,
It’s something I wanted to see in Java but it never happens.
I want to have an abstraction covering all natural numbers types (Int, Long, BigInteger or anyone else). The size in memory is finally just a technical concern. When I write extension function on Int for example, most of the time i want to write it on natural numbers.
I give you an example with fizzBuzz :
val Long.fizzBuzz: String
get() {
val isFizz = this % 3 == 0L
val isBuzz = this % 5 == 0L
return when {
isFizz && isBuzz -> "FizzBuzz"
isFizz -> "Fizz"
isBuzz -> "Buzz"
else -> this.toString()
}
}
I must write the following code for Int :
val Int.fizzBuzz: String
get() = this.toLong().fizzBuzz
Worse than that, I can’t write a method with same name for Iterable and Iterable :
val Iterable<Long>.fizzBuzz
get() = associate { value -> Pair(value, value.fizzBuzz) }.toSortedMap()
//does not compile
val Iterable<Int>.fizzBuzz
get() = associate { value -> Pair(value, value.fizzBuzz) }.toSortedMap()
With a natural number abstraction with all the base operators (+,-,*,/,%) such as Natural Numbers I could write really simpler code keeping the specific Natural Numbers properties.
I add that I don’t want to use ‘Number’ because FizzBuzz does not concern Real Numbers so I do not want BigDecimal, Float or Double !