Welcome to our Kotlin Generics tutorial! Today, we're going to explore a powerful feature of Kotlin that allows us to create more flexible and reusable code.
Generics are a feature in Kotlin that allows us to create classes, interfaces, and functions that work with multiple types. This means we can write a single piece of code that can handle different data types, making our code more flexible and reusable.
In Kotlin, we use type parameters to specify the types that a generic component can work with. Type parameters are denoted by angle brackets < >.
For example, consider the following generic class that represents a container:
class Container<T> {
private var item: T? = null
fun setItem(item: T) {
this.item = item
}
fun getItem(): T? {
return item
}
}In this example, T is a type parameter. The Container class can now hold items of any type.
To use a generic class or function, we need to specify the actual type that will be used. This is done by providing the type within the angle brackets when creating an instance or calling the function.
val container = Container<String>()
container.setItem("Hello, World!")
println(container.getItem()) // Output: Hello, World!In this example, we've created a Container instance that can hold strings. We've set an item of type String and retrieved it later.
Just like classes, we can also create generic functions. Here's an example of a generic function that swaps two values:
fun <T> swap(a: T, b: T): Pair<T, T> {
val temp = a
a = b
b = temp
return Pair(a, b)
}We can use this function with different data types:
val (a, b) = swap(1, 2)
println("$a, $b") // Output: 2, 1
val (c, d) = swap("Kotlin", "Java")
println("$c, $d") // Output: Java, KotlinIn Kotlin, every generic type has a corresponding non-generic version. This means that a generic class extends its non-generic counterpart.
For example, the List<T> generic class extends the List non-generic class. This allows us to use generic methods on non-generic collections.
val numbers = listOf(1, 2, 3, 4, 5)
println(numbers.max()) // Output: 5In this example, we've used the max() function on a non-generic List, but it's actually being called on the generic List<Int>.
What does the `T` in `Container<T>` represent?
That's it for our introduction to Kotlin Generics! In the next lesson, we'll dive deeper into using generics and explore some advanced concepts. Happy coding! 🎉