在Kotlin中获取泛型类型实例的最佳方式是什么?我希望找到以下C#代码的最佳近似值:
public T GetValue<T>() where T : new() {
return new T();
}
在Kotlin中获取泛型类型实例的最佳方式是什么?我希望找到以下C#代码的最佳近似值:
public T GetValue<T>() where T : new() {
return new T();
}
编辑:正如 comments 中提到的,这可能不是一个好主意.接受() -> T
分可能是实现这一目标最合理的方式.也就是说,下面的技术将实现您正在寻找的东西,如果不一定是以最惯用的方式的话.
不幸的是,您无法直接实现这一点:Kotlin因其Java血统而受到限制,因此泛型在运行时被删除,这意味着t不再可直接使用.使用反射和内联函数,您可以解决这个问题,不过:
/* 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
}