Effective Kotlin: Item 30 — Favor generic methods

In the incredible Effective Java, item 30 continues from the previous item covering generic methods in preference to a client needing explicit casts on input parameters and return values.

The implementation in Kotlin is not much different to Java just with the type parameter list specified between fun and the function name.

// Generic method
fun <T> union(vararg sets: Set<T>): Set<T> {
return sets.flatMap { it }.toSet()
}
val union = union<Number>(setOf<Int>(1, 2), setOf<Double>(3.1, 4.2))

Introducing generic methods shouldn’t break backwards compatibility in Kotlin unless of course it introduces a new generic class as discussed in item 29 so there is little reason to ignore the guidance, avoid the Any object where you can.

Each week I am looking at “items” from Joshua Bloch’s well-respected book, Effective Java to see how it applies to Kotlin. You can find the rest of the items I’ve covered at Effective Kotlin. Please let me know your thoughts.

Matt Dolan has been eating doughnuts and developing with Android since the dark days of v1.6.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store