How to create a generic method in Kotlin

5 Answers

0 votes
// You create a generic method in Kotlin by adding a type parameter in 
// angle brackets (e.g., <T>) before the function’s parameter list. 
// Kotlin’s syntax is simple: fun <T> methodName(param: T): T


fun <T> identity(value: T): T {
    return value
}

fun main() {
    println(identity(123))          // Int
    println(identity("Kotlin"))     // String
    println(identity(3.14))         // Double
}



/*
run:

123
Kotlin
3.14

*/

 



answered Apr 22 by avibootz
0 votes
// Generic Method With Two Type Parameters

fun <K, V> printPair(key: K, value: V) {
    println("$key = $value")
}

fun main() {
    printPair("Age", 65)
    printPair(101, "Employee ID")
    printPair("Pi", 3.14159)
}


/*
run:

Age = 65
101 = Employee ID
Pi = 3.14159

*/

 



answered Apr 22 by avibootz
0 votes
// Generic Method Using Class Parameters

fun <T> getTypeName(clazz: Class<T>): String {
    return clazz.simpleName
}

fun main() {
    println(getTypeName(String::class.java))  // "String"
    println(getTypeName(Int::class.java))     // "int"
}


/*
run:

String
int

*/

 



answered Apr 22 by avibootz
0 votes
// Generic Method Using Reified Type Parameters

// Kotlin’s reified type parameters (only allowed in inline functions) 
// let you access the type at runtime without passing a Class<T> manually.

inline fun <reified T> typeName(): String? {
    return T::class.simpleName
}

fun main() {
    println(typeName<String>())  // "String"
    println(typeName<Int>())     // "Int"
}


/*
run:

String
Int

*/

 



answered Apr 22 by avibootz
0 votes
fun <T> swap(list: MutableList<T>, i: Int, j: Int) {
    val temp = list[i]
    list[i] = list[j]
    list[j] = temp
}

fun <K, V> printPair(key: K, value: V) {
    println("$key = $value")
}

fun main() {
    val nums = mutableListOf(10, 20, 30, 40)
    println("Before swap: $nums")
    swap(nums, 1, 3)
    println("After swap:  $nums")

    printPair("Language", "Kotlin")
    printPair("Version", 1.9)
}


/*
run:

Before swap: [10, 20, 30, 40]
After swap:  [10, 40, 30, 20]
Language = Kotlin
Version = 1.9

*/

 



answered Apr 22 by avibootz
...