Member-only story
Kotlin Generic Functions -Class Simplifying for Every Developer
Generics in Kotlin enable you to write functions and classes that can work with any data type. They provide type safety, allowing you to catch type-related errors at compile time rather than runtime.
What are Generic Functions?
Generic functions are functions that can work with different types while ensuring type safety. They allow you to write functions without specifying the exact data type, making the code more versatile and reusable.
Declaring Generic Functions
In Kotlin, you can declare generic functions by using angle brackets <T>
, where T
is a type parameter. These type parameters act as placeholders for actual types. This allows you to write functions that can work with different types of data while maintaining type safety.
Code Example: Let’s create a generic function that takes two parameters and returns the maximum of the two. This function will work with any comparable data type.
fun <T : Comparable<T>> findMax(a: T, b: T): T {
return if (a > b) a else b
}
fun main() {
val maxInt = findMax(5, 10)
val maxString = findMax("apple", "banana")
println("Max Int: $maxInt")
println("Max String: $maxString")
}
Max Int: 10
Max String: banana