6

Here's the interface:

interface SomeInterface {
   companion object {
      const val MY_CONST = "the constant"
   }
}

And then, the class (without body because is only an example):

class SomeClass : SomeInterface

After this, when I try to call the constant through SomeClass, it not allows me:

SomeClass.MY_CONST

How do I resolve this?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Mário Henrique
  • 101
  • 2
  • 6

1 Answers1

6

Companion objects are not "inheritable"; they are fully qualified by the context in which they are defined (SomeInterface, in your case).

In essence, you'll need to write:

SomeInterface.MY_CONST
marianosimone
  • 3,366
  • 26
  • 32
  • Ok, thanks! I was hope that it possible. In java this is so easy :D – Mário Henrique Aug 12 '18 at 02:01
  • It is easy in Kotlin as well: just use the name where it's declared. Seriously, though, what are you trying to achieve? Maybe we can help you get to an acceptable design – marianosimone Aug 12 '18 at 06:06
  • I want to call the constants of the interface through the child class, just it. I don't want to call **SomeInterface.MY_CONST** but **SomeClass.MY_CONST**. But, if there's not a way to do this, I'll call from the Interface... sadly – Mário Henrique Aug 12 '18 at 15:15
  • I was asking if there was a design decision that makes you think that that would be a better API. There are alternatives like declaring the constant somewhere else (remember that you can have top-level declarations in Kotlin, or you could define an `object` to hold it) – marianosimone Aug 12 '18 at 16:01
  • It was just for maintain the code more concise, This interface is used in others classes, and theses classes should have the same constants. Declaring as an Object isn't good, because don't allow heritage. – Mário Henrique Aug 18 '18 at 01:21
  • I meant that you could define an `object` for the constant(s), and then keep your interface for any inheritance needs. But yeah, any design considerations are yours to make at that point :) – marianosimone Aug 18 '18 at 01:27