Generic functions in Kotlin allow developers to write flexible and reusable code that can work with different data types. They provide a way to create functions that can operate on various types without sacrificing type safety.
To define a generic function in Kotlin, you use angle brackets <>
after the function name to specify type parameters. Here's a simple example:
fun <T> printItem(item: T) {
println(item)
}
In this example, T
is a type parameter that can represent any type. You can call this function with different types:
printItem("Hello") // Prints: Hello
printItem(42) // Prints: 42
printItem(3.14) // Prints: 3.14
Kotlin generic functions can have multiple type parameters. This is useful when you need to work with different types within the same function:
fun <T, U> printPair(first: T, second: U) {
println("First: $first, Second: $second")
}
printPair("Age", 30) // Prints: First: Age, Second: 30
printPair(3.14, true) // Prints: First: 3.14, Second: true
You can add type constraints to generic functions to restrict the types that can be used. This is done using the :
operator followed by the upper bound:
fun <T : Comparable<T>> findMax(a: T, b: T): T {
return if (a > b) a else b
}
println(findMax(5, 10)) // Prints: 10
println(findMax("apple", "banana")) // Prints: banana
In this example, T
is constrained to types that implement the Comparable
interface.
T
for type, E
for element).To deepen your understanding of generics in Kotlin, explore these related topics:
By mastering generic functions, you'll be able to write more flexible and maintainable Kotlin code, adapting to various data types while ensuring type safety throughout your applications.