Member-only story
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.
Join medium to read all of my articles or subscribe for e-mail updates.