kotlin
  1. kotlin-generics

Kotlin Generics

Generics in Kotlin provide a way to create reusable code that can work with different types of objects. In this tutorial, we'll discuss how you can use generics in Kotlin.

Syntax

The syntax for defining a generic class in Kotlin is as follows:

class MyClass<T>(vararg items: T) {
    // Class definition
}

Example

Let's say you want to create a generic class that can work with different types of lists. Here's an example of how you can do that:

class ListWrapper<T>(val list: List<T>) {
    fun printList() {
        for (item in list) {
            println(item)
        }
    }
}

fun main() {
    val intList = listOf(1, 2, 3)
    val stringList = listOf("apple", "orange", "banana")

    val intWrapper = ListWrapper(intList)
    val stringWrapper = ListWrapper(stringList)

    intWrapper.printList()
    stringWrapper.printList()
}

Output

The output of this program would be:

1
2
3
apple
orange
banana

Explanation

In the example above, we define a generic class called ListWrapper that takes a type parameter T. The ListWrapper class has a property called list of type List<T>. This property can store any type of list.

In the printList method of the ListWrapper class, we loop through the list property and print each item.

In the main function, we create instances of the ListWrapper class with different types of lists. We create an instance of ListWrapper<Int> with an intList of type List<Int> and an instance of ListWrapper<String> with a stringList of type List<String>. We then call the printList method on each instance, which prints the items in the list.

Use

Generics in Kotlin can be used to create reusable classes and functions that can work with different types of objects. This is especially useful in cases where you want to write code that can work with multiple types of objects. For example, you can create a generic class that can work with different types of lists, sets, or maps.

Important Points

  • Generics in Kotlin provide a way to create reusable code that can work with different types of objects.
  • Generic classes are defined using the syntax class MyClass<T>(vararg items: T).
  • Generic functions are defined using the syntax fun <T> myFunction(item: T).
  • Type parameters are enclosed in angle brackets (< and >).
  • The letter T is often used as a type parameter name, but you can use any letter or word.

Summary

In this tutorial, we discussed how you can use generics in Kotlin. We covered the syntax, example, output, explanation, use, important points, and summary of generics in Kotlin. With this knowledge, you can now write generic classes and functions in Kotlin and create reusable code that can work with different types of objects.

Published on: