0

Is there any way to add a method to multiple classes, or reduce the amount of duplicated code needed to achieve the same.

At the moment I use the following (in this example to add a c method which count repetitions of items in the iterable):

/** Counts each of the distinct items. */
fun <T> Iterable<T>.c() = groupingBy { it }.eachCount()
/** Counts each of the distinct items. */
fun <T> Sequence<T>.c() = groupingBy { it }.eachCount()
/** Counts each of the distinct items. */
fun <T> Array<T>.c() = groupingBy { it }.eachCount()

I am wondering if there is a way to reduce the amount of code, at the moment I repeat that for all of the methods I want to be usable on any of the 3 types.

The only way I can find is to define an interface with the common methods, and then use a class to wrap each of the types with implements the common interface, but this seems like a lot of code for something that might be possible a simpler way.

jrtapsell
  • 6,719
  • 1
  • 26
  • 49

1 Answers1

2

What you currently have is the best you can do. If you look into the implementations of some standard library collection functions, you'll see them implemented individually for Iterable, Sequence, Array, and then the primitive array wrappers one by one.

For example, the groupingBy functions you're calling are 3 different ones, and they can be found here, here, and here. So even if you could somehow extend all these classes at the same time, you couldn't call the same groupingBy method on them, you'd need to handle them separately.

In conclusion, unfortunately the answer is no, it doesn't get any better than what you have in terms of the code you'll have to have in your application at the end of the day. If you have many cases like this, consider looking into code generation for all the different cases (which is also how the standard library code is maintained).

zsmb13
  • 85,752
  • 11
  • 221
  • 226