Generic functions

We’ve seen how you can declare a function that accepts or returns a generic type inside a generic class. You can also have generic functions declared inside a non-generic type. Declaring a generic function is done with the angle brackets after the fun keyword:

class NonGeneric {

fun <T> genericFunc(t: T) {
println(t.toString())
}
}

Calling the generic function is done by specifying the generic type in the angle brackets after the function name:

nonGeneric.genericFunc<String>("Kotlin")

Of course, if the compiler can infer the type passed to the function, you can omit specifying the type:

nonGeneric.genericFunc("Kotlin")
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.161.188