如何实例化通用类型的新实例 [英] How to instantiate a new instance of generic type
本文介绍了如何实例化通用类型的新实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在C#中,您可以对泛型施加新的约束,以创建泛型参数类型的新实例,在Kotlin中是否有等效项?
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?
现在我的解决方法是:
fun <T> someMethod(class : () -> T) {
val newInstance = class()
}
我这样叫someMethod()
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()
}
有可能吗?
推荐答案
当前,这是不可能的.您可以对问题 https://youtrack.jetbrains.com/issue/KT表示赞赏-6728 对该功能的新增功能进行投票.
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.
至少,您可以省略泛型类型,因为Kotlin可以推断出它:
At least, you can leave out the generic type because Kotlin can infer it:
someMethod(::MyClass)
这篇关于如何实例化通用类型的新实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文