36

What's the best way to get an instance of a generic type in Kotlin? I am hoping to find the best approximation of the following C# code:

public T GetValue<T>() where T : new() {
    return new T();
}
4

1 Answer 1

29

EDIT: As mentioned in comments, this is probably a bad idea. Accepting a () -> T is probably the most reasonable way of achieving this. That said, the following technique will achieve what you're looking for, if not necessarily in the most idiomatic way.

Unfortunately, you can't achieve that directly: Kotlin is hamstrung by its Java ancestry, so generics are erased at run time, meaning T is no longer available to use directly. Using reflection and inline functions, you can work around this, though:

/* We have no way to guarantee that an empty constructor exists, so must return T? instead of T */
inline fun <reified T : Any> getValue(): T? {
    val primaryConstructor = T::class.constructors.find { it.parameters.isEmpty() }
    return primaryConstructor?.call()
}

If we add some sample classes, you can see that this will return an instance when an empty constructor exists, or null otherwise:

class Foo() {}
class Bar(val label: String) { constructor() : this("bar")}
class Baz(val label: String)
    
fun main(args: Array<String>) {
    System.out.println("Foo: ${getValue<Foo>()}") // Foo@...
    // No need to specify the type when it can be inferred
    val foo : Foo? = getValue()
    System.out.println("Foo: ${foo}") // Foo@...
    System.out.println("Bar: ${getValue<Bar>()}") // Prints Bar@...
    System.out.println("Baz: ${getValue<Baz>()}") // null
}
3
  • 9
    Thanks for your answer. Looks like they weren't able to bring in the best from all modern languages then ... as a C# developer looking at Kotlin this is a bit of a letdown. They should have found some way to work some magic into the runtime. Feb 3, 2019 at 13:10
  • 9
    It's crazy that the decision to implement generics in Java via type erasure to ensure backwards compatibility has had such long-term negative effects on the JVM ecosystem. Apr 5, 2019 at 13:32
  • 1
    This is not possible in Kotlin version 1.4.32. I get this exception when I try to call T::class.java.constructors: This function has a reified type parameter and thus can only be inlined at compilation time, not called directly.
    – cbaldan
    Jul 15, 2021 at 2:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.