Generics

If you have done Java development, you are no doubt familiar with generics, otherwise known as “death by a thousand angle brackets”:

class TouchedByAnAngle<T> {
  private T thingy;

  public T getThingy() {
    return thingy;
  }

  public void setThingy(T replacement) {
    thingy = replacement;
  }
}

If you like Java’s generics, rest assured that Kotlin has a very similar system.

If you keep getting confused by Java’s generics, rest assured that, in time, you will be just as confused by Kotlin’s implementation.

And, if you are not that familiar with Java’s generics… that’s what the next section is for.

OK, What Are These For Again?

Kotlin, like Java, is “strongly typed”. This means each variable, property, parameter, and return value have a specific type, such as ArrayList or Axolotl or Thingy. The compiler will attempt to ensure that you only provide objects of valid types for these things.

We saw that back in the chapter on classes:

open class Animal

class Frog : Animal()

class Axolotl : Animal()

fun main() {
  val critter: Animal = Frog()

  if (critter is Frog) println("Ribbit!") else println("Ummm... whatever noise an axolotl makes!")
}

Here, critter is a variable of type Animal. We can assign an instance of a Frog to critter, because Frog extends Animal, and so Frog is a compatible type. But we could not assign an Int to critter, as Kotlin’s Int type does not extend Animal.

Now, suppose that we wanted a list of animals.

We could use the listOf() global function, supplied by Kotlin’s standard library, to create a list of animals:

val critters = listOf(Frog(), Axolotl())

From a type safety standpoint, though, it really is a List of Animal objects:

val critters: List<Animal> = listOf(Frog(), Axolotl())

Here we are saying that critters can only hold Animal objects. We cannot put an Int into the list, as Int is not an Animal.

Types like the List interface and the ArrayList implementation of List can use generics to constrain the type of objects that they work with. Therefore, when we are trying to work with a list of animals, we do not have to worry about accidentally encountering an integer, a string, or something else.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.