Decrease a value of any countable type (map)

I’m just trying to unify the map extension

fun <T> MutableMap<T, Int>.dec(key: T, value: Int = 1) = merge(key, value, Int::minus)

and stuck. How to make it with any countable type?

fun <K, V> MutableMap<K, V>.dec(key: K, value: Comparable<V>) = merge(key, value, Comparable::minus)

Actually, it’s possible to do a type converter like

when (value) {
  is Int -> Int
  is Float -> Float
  else Int
}

And I remember, there was something alike, but how to make it short?

I don’t think this is possible without using reflection. And even with reflection it won’t work with extension functions, only with member functions.

Kotlin doesn’t have a concept of a “countable type” as you call it and sadly, operators are not represented as interfaces as well. You can create such interface for your own classes and then you can make a generic dec() function, but it won’t work for existing types.

2 Likes

Maybe it’s possible to define V in MutableMap<K, V> and then make personal calculations?

Similar solutions are implemented in KMath. Inside algebra, it is possible to perform sum operation on a type the algebra covers. It is also possible to infer algebra in runtime, but it is not effective.

2 Likes