简体   繁体   中英

Type inference with lazy initialization and generic factory method in Kotlin

I have a factory method that produces some list of <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:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM