Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Generic Classes in Kotlin

Introduction to Generic Classes

Generic classes allow us to define classes with a placeholder for the type of data they will store. This provides type safety and code reusability, enabling us to create classes that can operate on different types without sacrificing performance or safety.

Defining a Generic Class

A generic class in Kotlin is defined using angle brackets (<>) to specify a type parameter. Here's how you can define a simple generic class:

class Box<T> (val item: T)

In this example, T is a type parameter that can be replaced with any type when an instance of Box is created.

Using a Generic Class

To use the generic class, you simply specify the type when creating an instance. For example:

val intBox = Box(10)
val stringBox = Box("Hello")

In this case, intBox is a Box that stores an Int, and stringBox is a Box that stores a String.

Generic Class with Multiple Type Parameters

Generic classes can also have multiple type parameters. Here's an example:

class Pair<A, B> (val first: A, val second: B)

This Pair class can hold two values of different types. For example:

val pair = Pair(1, "One")

Generic Constraints

Sometimes, you may want to restrict the types that can be used as type parameters. Kotlin provides generic constraints for this purpose. For example:

class Container<T> where T : Number (val item: T)

This Container class can only accept types that inherit from Number.

Example of a Generic Class in Action

Let's put everything together in a complete example where we create a generic class to hold a list of items:

class GenericList<T> {
private val items = mutableListOf<T>()
fun add(item: T) { items.add(item) }
fun get(index: Int): T = items[index]
}

We can now create a list of any type:

val intList = GenericList<Int>()
intList.add(1)
intList.add(2)
val firstItem = intList.get(0)

Conclusion

Generic classes in Kotlin provide a powerful way to create flexible and reusable code. By allowing type parameters, they enable developers to write code that works with any type while maintaining type safety. Understanding and utilizing generic classes is essential for effective Kotlin programming.