Kotlin, a modern programming language for JVM, allows you to write concise and expressive code. One of its powerful features is generics, which enable you to define classes and functions with a placeholder for type. This article will guide you through the process of defining generic classes in Kotlin with practical examples.
Understanding Generics
Generics help you create classes, methods, and interfaces with type parameters. This functionality enhances code reusability and safety by eliminating the need for casting and helps you avoid class cast exceptions during runtime.
Creating a Basic Generic Class
Let’s start by defining a simple generic class in Kotlin.
class Box<T>(var content: T) {
fun replaceContent(newContent: T) {
content = newContent
}
}
In the code above:
Tis a type parameter. It can be replaced by any type when you instantiate the class.contentis a variable of the typeT, meaning it can hold any data type.replaceContentis a function that allows you to change the content to a new value of the same type.
Instantiating Generic Classes
To create an instance of a generic class, provide the type as a parameter:
fun main() {
val intBox: Box<Int> = Box(123)
println(intBox.content) // Prints: 123
intBox.replaceContent(456)
println(intBox.content) // Prints: 456
val stringBox = Box("Hello")
println(stringBox.content) // Prints: Hello
stringBox.replaceContent("World")
println(stringBox.content) // Prints: World
}
Here:
Box<Int>creates a Box that holds integer values.Box("Hello")creates a Box capable of holding String.
Generic Constraints
Sometimes, you may want to limit the types that can be used as arguments for a generic type. This is achieved through constraints. For instance, you can specify that a type must inherit from a specific superclass or implement an interface.
class NumberBox<T : Number>(val number: T)
fun main() {
val intBox = NumberBox(10) // Works fine
val doubleBox = NumberBox(10.5) // Works fine
// val stringBox = NumberBox("Hello") // Compilation error
}
In this example, T is constrained to be a subtype of Number.
Variance in Generics
Kotlin's generics support both covariant and contravariant generic types, helping you manage flexibility when dealing with type parameters.
Covariance allows you to use a subtype as the actual type:
// Covariant
class Covariant<out T>(val value: T)
fun main() {
val strCovariant: Covariant<String> = Covariant("Hello")
val anyCovariant: Covariant<Any> = strCovariant // OK
println(anyCovariant.value)
}
Contravariance allows you to use a supertype as the actual type:
// Contravariant
class Contravariant<in T>
fun main() {
val strContravariant: Contravariant<String> = Contravariant()
val anyContravariant: Contravariant<Any> = strContravariant // OK
}
Conclusion
Generics in Kotlin offer a robust way to write type-safe and reusable code. From defining basic generic classes to applying constraints and variance, mastering these techniques will empower you to write cleaner Kotlin code. Practice defining and using generics in your applications to fully harness their potential.