在Kotlin中实例化一个genericstypes

在Kotlin中获得一个genericstypes的实例的最好方法是什么? 我希望find以下C#代码的最佳(如果不是100%完美)近似值:

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

编辑:正如评论中提到的,这可能是一个坏主意。 接受一个() -> T可能是实现这个最合理的方法。 也就是说,下面的技巧可以达到你要找的东西,不一定是最习惯的方式。

不幸的是,你不能直接实现这个目标:Kotlin受到其Java系统的束缚,所以generics在运行时被删除,这意味着T不再可以直接使用。 使用reflection和内联函数,你可以解决这个问题,但是:

 /* Convenience wrapper that allows you to call getValue() instead of of getValue(Type::class) */ inline fun  getValue() : T? = getValue(T::class) /* We have no way to guarantee that an empty constructor exists, so must return T? instead of T */ fun  getValue(clazz: KClass) : T? { clazz.constructors.forEach { con -> if (con.parameters.size == 0) { return con.call() } } return null } 

如果我们添加一些示例类,您可以看到,如果存在空的构造函数,将返回一个实例,否则返回null:

 class Foo() {} class Bar(val label: String) { constructor() : this("bar")} class Baz(val label: String) fun main(args: Array) { System.out.println("Foo: ${getValue()}") // 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()}") // Prints Bar@... System.out.println("Baz: ${getValue()}") // null }