Is it possible to have a function that returns a generic type? Something like:
fun <T> doSomething() : T {
when {
T is Boolean -> somethingThatReturnsBoolean()
T is Int -> somethingThatReturnsInt()
else -> throw Exception("Unhandled return type")
}
}
The print() function is an example of a generic function. A generic function is simply a function that performs a common task by dispatching its input to a particular method-function that is selected on the basis of the class of the input to the generic function.
(Yes, this is legal code; see Java Generics: Generic type defined as return type only.) The return type will be inferred from the caller. However, note the @SuppressWarnings annotation: that tells you that this code isn't typesafe. You have to verify it yourself, or you could get ClassCastExceptions at runtime.
Generic Method: Generic Java method takes a parameter and returns some value after performing a task. It is exactly like a normal function, however, a generic method has type parameters that are cited by actual type. This allows the generic method to be used in a more general way.
Generics allow creating 'type variables' which can be used to create classes, functions & type aliases that don't need to explicitly define the types that they use. Generics makes it easier to write reusable code.
You can use reified type to capture its class literal, like this:
inline fun <reified T> doSomething() : T {
return when (T::class.java) {
Boolean::class.java -> somethingThatReturnsBoolean() as T
Int::class.java -> somethingThatReturnsInt() as T
else -> throw Exception("Unhandled return type")
}
}
But you also must convince the compiler that T is Boolean or T is Int, as in the example, with unchecked cast.
reified
makes real T's type accessible, but works only inside inline functions. If you want a regular function, you can try:
inline fun <reified T> doSomething() : T = doSomething(T::class.java)
fun <T> doSomething(klass: Class<T>): T {
return when (klass) { ... }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With