Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A function with generic return type

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")
    }
}
like image 688
Johnny Avatar asked May 15 '17 15:05

Johnny


People also ask

What is generic function example?

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.

Is it possible to return a generic type in Java?

(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.

What is generic function in Java?

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.

What is generic type in TypeScript?

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.


1 Answers

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) { ... }
}
like image 57
Miha_x64 Avatar answered Oct 20 '22 07:10

Miha_x64