How to instantiate a new instance of generic type

2019-02-08 16:01发布

问题:

In C# you can place a new constraint on a generic to create a new instance of the generic parameter type, is there an equivalent in Kotlin?

Right now my work around is this:

fun <T> someMethod(class : () -> T) {
    val newInstance = class()
}

and I'm calling someMethod() like this

someMethod<MyClass>(::MyClass)

but I would like to do something like this:

fun <T : new> someMethod() {
    val newInstance = T()
}

Is that possible?

回答1:

Currently, that's not possible. You can give a thumbs-up for the issue https://youtrack.jetbrains.com/issue/KT-6728 to vote for the addition of this feature.

At least, you can leave out the generic type because Kotlin can infer it:

someMethod(::MyClass)


标签: kotlin