[英]Type inference with lazy initialization and generic factory method in Kotlin
I have a factory method that produces some list of <T>
: 我有一个工厂方法,它产生
<T>
一些列表:
inline fun <reified T> getObject(fileName: String): List<T>
The factory method should be used for lazy initialization like this: 应该将工厂方法用于延迟初始化,如下所示:
val points: List<Point> by lazy {
ObjectFactory.getObject(pointsFileName)
}
Now the Kotlin compiler obviously has not enough type information inside the lambda and complains: 现在Kotlin编译器显然在lambda内部没有足够的类型信息,并抱怨:
Type inference failed:
Not enough information to infer parameter T in
inline fun <reified T> getObject(fileName: String): List<T>
Please specify it explicitly.
The compiler is not considering the type to which the result of the lazy initialization will be assigned. 编译器没有考虑将惰性初始化的结果分配给的类型。 I can work around this by providing the type locally, but it's not pretty:
我可以通过在本地提供类型来解决此问题,但这不是很漂亮:
val points by lazy {
val pointsToCommunicateType: List<Point> =
ObjectFactory.getObject(pointsFileName)
pointsToCommunicateType
}
What is the right way to do this? 什么是正确的方法?
您可以这样指定类型:
ObjectFactory.getObject<Point>(pointsFileName)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.