Kotlin Abstract Protected Property

Eliezer picture Eliezer · Sep 21, 2016 · Viewed 8.5k times · Source

If I have the following class hierarchy:

abstract class Foo<out T : Bar>() {
  abstract protected val thing: T
}

class Baz : Foo<BarImpl> {
  override protected val thing: T = ...
}

I get a warning on Baz::thing saying:

Redundant visibility modifier

Does that mean the compiler treats it as protected without you needing to specify that, or that it has to be public?

Answer

Jayson Minard picture Jayson Minard · Sep 22, 2016

You will receive an IDE inspection style warnings in Kotlin for things like extra semi-colons you don't need, an extra generic type parameters that can already be inferred, and more. Yours for redundant visibility modifier is along the same lines.

If you expand the inspection message you will see the full text:

This inspection reports visibility modifiers which match the default visibility of an element (public for most elements, protected for members that override a protected member).

And you can turn the inspection off within your IDE if you no longer what to see it.

A few more notes about this:

When overriding a method or member of an ancestor class you are already at the same access level as when it was declared. Saying protected is stating the obvious (to the compiler which knows it is protected).

You are allowed to restate the access modifier again if you want. And you can open it up more, by changing it to public. But you cannot restrict it further, for example going to private (because if it is private how could you override it, that idea is incompatible with override) which becomes a compiler error.