Kotlin: class inherits of an interface that contains companion object, but doesn't have access to the constants of the interface
Asked Answered
P

1

7

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?

Pragmatic answered 11/8, 2018 at 0:58 Comment(0)
K
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
Kenn answered 11/8, 2018 at 4:53 Comment(6)
Ok, thanks! I was hope that it possible. In java this is so easy :DAarika
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 designKenn
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... sadlyAarika
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)Kenn
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.Aarika
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 :)Kenn

© 2022 - 2024 — McMap. All rights reserved.