在 Kotlin 中使用惰性初始化和通用工厂方法进行类型推断
Type inference with lazy initialization and generic factory method in Kotlin
我有一个工厂方法可以生成一些列表 <T>
:
inline fun <reified T> getObject(fileName: String): List<T>
工厂方法应该像这样用于惰性初始化:
val points: List<Point> by lazy {
ObjectFactory.getObject(pointsFileName)
}
现在 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.
编译器没有考虑延迟初始化的结果将分配给的类型。我可以通过在本地提供类型来解决这个问题,但它并不漂亮:
val points by lazy {
val pointsToCommunicateType: List<Point> =
ObjectFactory.getObject(pointsFileName)
pointsToCommunicateType
}
正确的做法是什么?
您可以这样指定类型:
ObjectFactory.getObject<Point>(pointsFileName)
我有一个工厂方法可以生成一些列表 <T>
:
inline fun <reified T> getObject(fileName: String): List<T>
工厂方法应该像这样用于惰性初始化:
val points: List<Point> by lazy {
ObjectFactory.getObject(pointsFileName)
}
现在 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.
编译器没有考虑延迟初始化的结果将分配给的类型。我可以通过在本地提供类型来解决这个问题,但它并不漂亮:
val points by lazy {
val pointsToCommunicateType: List<Point> =
ObjectFactory.getObject(pointsFileName)
pointsToCommunicateType
}
正确的做法是什么?
您可以这样指定类型:
ObjectFactory.getObject<Point>(pointsFileName)