Wheat Wizard
Wheat Wizard

Reputation: 4219

Why can't an object have a companion object?

I have an object for my tests using Spek

object CodeTest : Spek({
  describe ("feature1") {
    it("has correct code") {
      assertTrue(123, 120 + 3)
    }
  }
})

I would like to initialize some constants.

I can't just dump the constants into the body of the CodeTest:

object CodeTest : Spek({
  describe ("feature1") {
    it("has correct code") {
      assertTrue(ALL_GOOD, 120 + 3)
    }
  }
}) {
  private const val = ALL_GOOD = 123
}

Because they won't be available for use in the scope in which I want to use them. The solution for a class, and a very straight forward solution overall, would be to use a companion object:

object CodeTest : Spek({
  describe ("feature1") {
    it("has correct code") {
      assertTrue(ALL_GOOD, 120 + 3)
    }
  }
}) {
  companion object Codes {
    private const val ALL_GOOD = 123
  }
}

However the compiler informs me that I can't add a companion object to another object. So ok, I can change my object to a class, problem solved I guess.

But it still is a singleton. And I don't see any way that a companion object can ever make an object not a singleton. So why is this restriction in place? Why must it be a class in order for it to have a companion object?

Upvotes: 0

Views: 613

Answers (1)

Tenfour04
Tenfour04

Reputation: 93902

Companion objects are not exactly analogous to what a class object is (the static members of a class) in Java. For the use case you're describing, the typical way to organize your code would be to define a top-level property/constant outside the class definition, private to the file.

private const val ALL_GOOD = 123

object CodeTest : Spek({
  describe ("feature1") {
    it("has correct code") {
      assertTrue(ALL_GOOD, 120 + 3)
    }
  }
})

Even if your class was a class and not an object, I would still do it this way for private constants. There's no need for instantiating a singleton if it's solely to store some constants.

Upvotes: 1

Related Questions