如何将类型参数传递给泛型类的构造函数引用? [英] How to pass a type parameter to a generic class constructor reference?
问题描述
假设以下代码:
Assume the following code:
class ConstructMe<T> {}
data class Test<T> constructor(var supplier: () -> ConstructMe<T>) {}
fun main(args: Array<String>) {
works<Int>()
breaks<Int>()
}
fun <T> works() {
Test<T>({ ConstructMe<T>() }) // (1) any one class type parameter can be removed like:
Test({ ConstructMe<T>() }) // (2) still works (class type inferred by argument type)
Test<T>({ ConstructMe() }) // (3) still works (argument type inferred by class type)
}
fun <T> breaks() {
Test<T>(::ConstructMe) // type interference failed (should probably work like (3); compiler improvement possible?)
Test<T>(::ConstructMe<T>) // type interference failed & type argument not allowed (language change necessary?)
}
我碰到过这个通过传递JavaFX属性( SimpleIntegerProperty
, SimpleStringProperty
,...和 SimpleObjectProperty< T> / code>)到一个泛型类的构造函数
() - >属性< T>
参数,其中传递 :: SimpleIntegerProperty
时没有问题,而 :: SimpleObjectProperty
失败,像上面的示例代码。
I've run into this by passing JavaFX properties (SimpleIntegerProperty
, SimpleStringProperty
, ... and SimpleObjectProperty<T>
) to a generic class constructors () -> Property<T>
argument, where passing ::SimpleIntegerProperty
works without a problem, while ::SimpleObjectProperty
fails like the above example code.
是否可以在此处改进编译器或允许将类型参数传递给构造函数/函数引用?
在这里使用简单lambda表达式的构造函数引用是否有意义?它是否有不同的编译方式?
Is it possible to improve the compiler here or to allow passing type parameters to constructor/function references? Does it even make sense to use constructor references over simple lambda expressions here? Does it compile any differently?
推荐答案
是的,可以在这里改进编译器。它可以推断 ConstructMe
的类型参数。查看问题 https://youtrack.jetbrains.com/issue/KT-10711 。
Yes, it is possible to improve the compiler here. It could infer type parameter for ConstructMe
. See issue https://youtrack.jetbrains.com/issue/KT-10711.
对于非内联的ounter函数(在这种情况下,它是Test的构造函数),构造函数的lambda和callable引用没有区别。对于这两种情况,编译器都会创建一个具有方法 invoke
的匿名类,该类创建 ConstructMe
的实例。
For non-inline ounter function(in this case it is constructor of Test) there is no difference between lambda and callable reference to constructor. For both cases compiler creates anonymous class which has method invoke
that creates an instance of ConstructMe
.
但是,在构造函数有很多参数的情况下,可调用引用比lambda更方便。
But callable reference is more convenient than lambda in cases where constructor has a lot of parameters.
这篇关于如何将类型参数传递给泛型类的构造函数引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!