首页 > 解决方案 > 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

我怎样才能使这行代码工作?

标签: springkotlin

解决方案


之后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 网站上文档的某些部分,以更好地了解所有内容:

https://kotlinlang.org/docs/home.html


推荐阅读