spring - Spring Kotlin - 将对象更改为类并出错
问题描述
我从这里更改了我的代码:
object SomeHelper{}
对此:
@Component
class SomeHelper(private val anAttribute: AnAttributeService){}
AnAttributeService
看起来像这样:
@Service
class AnAttributeService(private val myLoader: MyLoader){}
这是MyLoader
:
interface MyLoader {
fun loadSomething()
}
在我的测试课中,我写了这样的东西:
class SomeHelperTester{
val cut = SomeHelper
//...
}
当 SomeHelper 是一个对象时它曾经可以正常工作,但现在当我写
val cut = SomeHelper(anAttribute = AnAttributeService(myLoader = MyLoader))
MyLoader 带有红色下划线,并带有错误提示Classifier MyLoader does not have a companion object, and thus must be initialized
我怎样才能使这行代码工作?
解决方案
之后myLoader =
你需要提供一个 type 的实例MyLoader
。你不能只说MyLoader
那里。
如果MyLoader
是一个类,您可以将其更改为MyLoader()
. 但是你定义MyLoader
为一个接口,这意味着你需要为它提供一个实现。
最常见的方法是创建一个扩展接口的类并创建一个实例。例如:
class MyLoaderImp: MyLoader {
override fun loadSomething() {
//implementation here
}
}
那么你可以做
val cut = SomeHelper(anAttribute = AnAttributeService(myLoader = MyLoaderImp()))
另请注意,在 kotlin 中,您不需要明确提及参数名称,除非您以其他顺序提供它们或省略一些,因此这也是有效且更短的
val cut = SomeHelper(AnAttributeService(MyLoaderImp()))
或者,您可以在这样的匿名类中提供实现
val cut = SomeHelper(AnAttributeService(object: MyLoader{
override fun loadSomething() {
//implementation here
}
}))
在我看来,您仍然缺乏很多关于 kotlin 和一般编程的基础知识。我建议您研究 kotlin 网站上文档的某些部分,以更好地了解所有内容:
推荐阅读
- regex - 使用 sed 向后删除特定的空格
- java - 插入排序的变量赋值问题
- python - 在 Django 中按标签过滤博客
- php - 显示带有复选框的数据库并将选定的数据查询到另一个 php 文件中
- c# - 变量不会在winforms中更新
- ios - 如何在我的 UITableViewCell 类的所有实例中访问模型类的一个特定实例的属性?
- algorithm - 网格中最长的“随机不相交”路径
- python - Python 中元编程的用例是什么?
- netty - Netty:如何更改套接字上的 InterestOps?
- python - 如何在没有 BioPython 库的情况下将 RNA 翻译成蛋白质