问题描述
免责声明:对于Kotlin来说,这可能是一个易于解决的问题或被误解的基础知识。
Disclaimer: New to Kotlin, may be a easy to solve issue or misunderstood basics.
我正尝试在其中插入特定接口的Spring实现列表。
I am trying to inject a List of a specific interface's Spring implementations, in a regular java class this have been easy like this:
@Autowired
List<IMyClass> myClassList;
但是在Kotlin中,执行以下操作会给我一个错误
But in Kotlin doing the following gives me a error
@Autowired
lateinit private var myClassList: List<IMyClass<Any>>
// No beans of '? extends IMyClass<Object>' or 'List<? extends IMyClass<Object>>' types found
这样做:
@Autowired
lateinit private var myClassList: List<IMyClass<*>>
进行注入工作,但不允许我使用接口中定义的函数通用对象作为输入
Makes the injection work but doesn't allow me to use a function defined in the interface that takes a generic object as input
// Out-projected type 'IMyClass<*>' prohibits the use of 'public abstract fun myFunction(obj: T!): T! defined in com.path.IMyClass'
那么我应该如何解决呢?
So how am I supposed to solve this? Is it easier to rewrite the interface in Kotlin with some specific syntac?
推荐答案
您在Java中所做的事情只是使用隐式操作?通配符。因此,这里有2种方式:
Thing you're doing in Java is just using implicit wildcard. So you have 2 ways here:
- 尝试重构API并注入
List< IMyClass<的列表?扩展SomeInterface>>>
- 使用注入的
List< IMyClass< *>>
但将其强制转换明确显示您需要的东西,即myClassList as List< IMyClass< Any>>
- Try to refactor API and inject list of
List<IMyClass<? extends SomeInterface>>
- Use injected
List<IMyClass<*>>
but cast it explicitly to thing you need, i.e.myClassList as List<IMyClass<Any>>
在这里,科特林的抹除更为明确。如果您不知道那里有什么类型,我们就不能保证您的代码能正常工作,因为kotlin中有这样的类型: Nothing
,而该实例不能存在。
Thing here is kotlin's erasure is more explicit. If you don't know what type is there — we can't guarantee your code will work, because there is such type in kotlin as Nothing
, instance of which can't exist.
这篇关于Spring注入kotlin中通用接口实现的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!