I am currently studying Kotlin and trying to create an extension method (infix), which works on all numeric types ( Byte, Long, Floatetc.). It should work as a Python statement %:
4 % 3 == 1 // only this is the same as Java %
4 % -3 == -2
-4 % 3 == 2
-4 % -3 == -1
... or like Java Math.floorMod, but it should also work with Doubleor Float:
-4.3 % 3.2 == 2.1000000000000005
or with any possible combination of these types
3 % 2.2 == 0.7999999999999998
3L % 2.2f == 0.7999999999999998
The following works as intended, but only for two Doubleor two Int:
inline infix fun Double.fmod(other: Double): Number {
return ((this % other) + other) % other
}
inline infix fun Int.fmod(other: Int): Number {
return ((this % other) + other) % other
}
// test
fun main(args: Array<String>) {
println("""
${-4.3 fmod 3.2} == 2.1000000000000005
${4 fmod 3} == 1
${+4 fmod -3} == -2
${-4 fmod 3} == 2
${-4 fmod -3} == -1
""")
}
Replacing Intwith Number, I get the following error messages:
Error:(21, 18) Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
@InlineOnly public operator inline fun BigDecimal.mod(other: BigDecimal): BigDecimal defined in kotlin
Error:(21, 27) Public-API inline function cannot access non-public-API 'internal open fun <ERROR FUNCTION>(): [ERROR : <ERROR FUNCTION RETURN TYPE>] defined in root package'
Error:(21, 36) Public-API inline function cannot access non-public-API 'internal open fun <ERROR FUNCTION>(): [ERROR : <ERROR FUNCTION RETURN TYPE>] defined in root package'
How can I achieve this for each type of number without copying an insert for each combination of types?