Reputation: 10559
In Kotlin, we can define nested interfaces. If the outer interface is generic (here just to simulate a proper Self
meta-type, but one can imagine other uses), can I refer to its type parameter from the inner type?
That is, I want to achieve (an equivalent of) this:
interface JsonRepresentable<Self: JsonRepresentable<Self>> {
fun toJson(): String
interface Companion {
operator fun invoke(json:String): Self?
}
}
Upvotes: 0
Views: 318
Reputation: 6419
No, you can't. An interface can't be a non-static inner class, which is a platform constrain that can't be overcame by Kotlin. I know it would be pretty useful to constrain how the companion object should be, but this haven't been considered yet. I don't know if JetBrains will ever take this suggestion seriously.
In your attempt, those two interfaces are NOT related at all, except that you can find KClass<Compaion>
in JsonRepresentable::class.nestedClasses
. The relationship between these interfaces can be compared to the relationship between a Java static inner class and its declaring class.
Upvotes: 2