0
0
Kotlinprogramming~5 mins

Multiple type parameters in Kotlin

Choose your learning style9 modes available
Introduction
Using multiple type parameters lets you create flexible functions or classes that work with different types at the same time.
When you want a function to accept two different types of inputs and work with both.
When creating a class that holds or processes two different types of data together.
When you want to write reusable code that can handle pairs or combinations of types.
When you want to avoid writing similar code for different type combinations.
Syntax
Kotlin
fun <T, U> functionName(param1: T, param2: U): String {
    // function body
}
Type parameters are listed inside angle brackets < > separated by commas.
You can use any names for type parameters, but T and U are common simple choices.
Examples
A function that takes two different types and returns a string describing them.
Kotlin
fun <T, U> pairToString(first: T, second: U): String {
    return "First: $first, Second: $second"
}
A class holding two values of different types with a method to describe them.
Kotlin
class Box<T, U>(val first: T, val second: U) {
    fun describe() = "Box contains: $first and $second"
}
Sample Program
This program defines a function with two type parameters and calls it with different types to show how it works.
Kotlin
fun <T, U> combineToString(a: T, b: U): String {
    return "Combined: $a and $b"
}

fun main() {
    val result1 = combineToString(10, "apples")
    val result2 = combineToString("Hello", 3.14)
    println(result1)
    println(result2)
}
OutputSuccess
Important Notes
You can have as many type parameters as you need, separated by commas.
Type parameters help keep your code safe by checking types at compile time.
Using descriptive names for type parameters can make your code easier to understand.
Summary
Multiple type parameters let you work with different types in one function or class.
They are listed inside < > separated by commas.
This makes your code flexible and reusable for many type combinations.