Effective Kotlin: Item 29 — Favor generic types

Matthew Dolan
2 min readDec 1, 2018

As with Java, there is no excuse in forcing clients to cast types when using your code especially when making a class generic is often trivial. Item 29 of Joshua Bloch’s brilliant Effective Java covers this by showing an example of generifying a Stack class which might look as follows in Kotlin:

class Stack(initialCapacity: Int = 16) {
private var elements = arrayOfNulls<Any?>(initialCapacity)
private var size = 0

val isEmpty = size == 0

fun push(e: Any) {
ensureCapacity()
elements[size++] = e
}

fun pop()…

--

--

Matthew Dolan

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