Kotlin泛型工厂方法编译报错:需将返回类型从ArrayList<T>改为特定对象ArrayList
错误原因
- Kotlin编译器无法自主感知你
when分支的类型判断逻辑和泛型参数T的绑定关系,即使你通过modelClass的匹配保证了返回集合类型和T一致,编译器也不会自动识别这种对应关系,因此会报类型不匹配的编译错误。
修复方案
方案1:手动安全强转(最快捷)
你可以手动将返回的集合强转为ArrayList<T>,因为业务逻辑已经保证类型匹配,这个强转是安全的,只需添加注解忽略编译器的未检查转换警告即可,修复后代码如下:
// Factory interface interface IFactory { fun <T: Contentable> create(modelClass: Class<T>): ArrayList<T> } // Factory class class InstructFactory(private val details: Details) : IFactory{ @Suppress("UNCHECKED_CAST") override fun <T: Contentable> create(modelClass: Class<T>): ArrayList<T> { return when(modelClass) { FirstClass::class.java -> details.firstList as ArrayList<T> SecondClass::class.java -> details.secondList as ArrayList<T> else -> details.thirdList as ArrayList<T> } } }
方案2:结合reified泛型优化调用体验(Kotlin专属写法)
如果想要简化调用时的代码,不需要每次手动传入Class对象,可以用inline+reified实化泛型的语法糖优化,优化后代码如下:
interface IFactory { fun <T: Contentable> create(modelClass: Class<T>): ArrayList<T> // 扩展方法,用reified泛型自动捕获泛型类型 inline fun <reified T: Contentable> create(): ArrayList<T> = create(T::class.java) } class InstructFactory(private val details: Details) : IFactory{ @Suppress("UNCHECKED_CAST") override fun <T: Contentable> create(modelClass: Class<T>): ArrayList<T> { return when(modelClass) { FirstClass::class.java -> details.firstList as ArrayList<T> SecondClass::class.java -> details.secondList as ArrayList<T> else -> details.thirdList as ArrayList<T> } } } // 调用示例 val factory = InstructFactory(yourDetailsInstance) val firstClassList = factory.create<FirstClass>() val secondClassList = factory.create<SecondClass>()
这个方案不需要改动原有逻辑,只需要新增一个inline扩展方法,调用时可以直接指定泛型类型,不需要手动传入类对象。
内容的提问来源于stack exchange,提问作者nayan dhabarde
相关产品推荐
相关产品推荐

