5

In Kotlin 1.4.30, when I type

open interface I

the Kotlin compiler warns me that modifier 'open' is redundant for 'interface'. This makes complete sense: Of course interfaces are open, otherwise they would be useless.

However, the reflection library seems to contradict this:

interface I
println(I::class.isOpen) // prints 'false'

How does this make sense? The KDoc of isOpen is very brief:

true if this class is open.

What exactly is the definition of "open" in Kotlin? I thought it meant "open to the possibility of being sub-typed by classes outside this file".

blubb
  • 9,510
  • 3
  • 40
  • 82

1 Answers1

4

The methods isFinal, isOpen, isAbstract, isSealed were designed such that only one of them returns true for all KClass instances.

Source: this comment in KT-19850.

Since interfaces are abstract, I::class.isAbstract == true. Combined with the above design goal, I::class.isOpen == false results.

Please upvote KT-19850 to help getting this surprising behavior fixed.

blubb
  • 9,510
  • 3
  • 40
  • 82
  • Interfaces being abstract but not open make sense when you consider what it implies. You can instantiate open classes while it's impossible for abstract ones. – Pawel Feb 26 '21 at 14:56
  • 1
    @Pawel I'm not convinced by your explanation: if "open" implied "can be instantiated", I would expect `open interface` to throw a compiler error. Instead, I am getting a warning that tells me "you don't need to write `open`, that's already implied by `interface`". – blubb Feb 26 '21 at 15:04
  • @Pawel Also, a `sealed class` has `isAbstract == false` even though it cannot be instantiated. – blubb Feb 26 '21 at 15:08
  • 1
    Yes, I understand abstract to be a superset of open. Open does not imply "instantiable". – Tenfour04 Feb 26 '21 at 15:29