Skip to content

Kotlin Generics

Devrath edited this page Feb 10, 2024 · 1 revision

Example-1: Calling a function that has generic parameters

output

Result:-> 6
Result:-> x-y-x

code

fun main(args: Array<String>) {
    // Pass Integers
    demoOne(1,2,3)
    // Pass Strings
    demoOne("x","y","x")
}

fun <T,R,P>demoOne(a : T, b:R, c:P){
    if(a is Int && b is Int && c is Int){
        val result = a+b+c
        println("Result:-> $result")
    }else if(a is String && b is String && c is String){
        val result = a.plus("-").plus(b).plus("-").plus(c)
        println("Result:-> $result")
    }
}
Clone this wiki locally