Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

Defining Generics in Kotlin

Introduction to Generics

Generics are a powerful feature in Kotlin that allow developers to write flexible and reusable code. By using generics, you can create classes, interfaces, and functions that can operate on different data types while maintaining type safety. This enables you to define a single implementation that works with various types, reducing code duplication and enhancing maintainability.

Defining Generic Classes

A generic class in Kotlin is defined using angle brackets (<>) containing a type parameter. This parameter acts as a placeholder for the actual type that will be passed when an instance of the class is created.

Example: Generic Box Class

Here is how you can define a generic class:

class Box(var item: T)

In this example, we define a class named Box that can hold an item of any type T. The type parameter T will be replaced with a concrete type when an instance of Box is created.

Creating Instances of Generic Classes

After defining a generic class, you can create instances of it by specifying the actual type you want to use.

Example: Using the Box Class

Here is an example of creating instances:

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

In this case, intBox is a box that holds an Int type, and stringBox holds a String type. You can access the item in the box using the property item:

println(intBox.item) // Output: 123

Defining Generic Functions

Just like classes, you can also define generic functions. A generic function allows you to work with different types without sacrificing type safety.

Example: Generic Function

Here is how to define a generic function:

fun printItem(item: T) {
   println(item)
}

This function takes a parameter of type T and prints it. You can call this function with any type:

printItem(42)
printItem("Hello")

The output will be:

42
Hello

Constraints on Type Parameters

You can also apply constraints on type parameters to restrict the types that can be used. This is done using the where clause.

Example: Constrained Generic Function

Here is an example with a constraint:

fun add(a: T, b: T): T {
   return (a.toDouble() + b.toDouble()) as T
}

This function only accepts parameters that are subclasses of Number, ensuring that you can safely perform arithmetic operations.

Conclusion

Generics in Kotlin provide a robust way to create flexible and type-safe code. By defining generic classes and functions, you can enhance code reusability and maintainability. Understanding how to define and use generics will significantly improve your Kotlin programming skills.