Home > Software design >  Spring Kotlin - Changed object to class and got error saying "classifier does not have a compan
Spring Kotlin - Changed object to class and got error saying "classifier does not have a compan

Time:11-03

I changed my code from this

object SomeHelper{}

to this

@Component 
class SomeHelper{}

In my test class I wrote something like this:

class SomeHelperTester{
val cut = SomeHelper
//...
}

which used to work fine when SomeHelper was an object, but now the line val cut = SomeHelper is underlined with an error saying Classifier SomeHelper does not have a companion object, and thus must be initialized. How can I make this line of code work?

CodePudding user response:

just add () behind it, like

val cut = SomeHelper()

CodePudding user response:

This is down to the difference between an object (a singleton, with exactly one instance), and a class (of which you can create as many instances as you like).

When you declare a variable with an initialiser (as you do with cut), the initialiser needs to evaluate to an object. When SomeHelper was declared as an object, then it evaluates to the one and only instance, which works fine as an initialiser. But when it's declared as a class, then the class name alone doesn't mean anything.

What you need to do is to create an instance of the class, by calling its constructor. In this case, since you haven't specified a constructor, you get the default one which takes no parameters. So you can simply call it by appending an empty pair of brackets, and use that as the initialiser:

val cut = SomeHelper()
  • Related