Kotlin cannot access a protected abstract method

I have the following class structure:

abstract class Abstr{
    protected abstract fun m()
}

class Child : Abstr(){
    private val subChild: Abstr = Child()

    override fun m() = subChild.m()// Error:(12, 18) Kotlin: Cannot access 'm': it is protected in 'Abstr'
}

I got an exception Kotlin: Cannot access 'm': it is protected in 'Abstr'

This is a bit confusing because the same structure is legal for java.

According to kotlin docs

  • protected - visible inside this class only + visible in subclasses;

Is this a bug or an expected behavior?

+6
source share
3 answers

This is a developed behavior.

The protected modifier in Kotlin is similar to Java, but has additional restrictions.

Protectd in Java :

  • Visible to inhalation
  • Visible in package

Protectd in Kotlin :

  • Visible to inhalation

So, according to this code, we cannot access the protected method

class Child : Abstr(){
    private val subChild: Abstr = Child()

    override fun m() = subChild.m() //Trying to access not inherited method 
}

Java, :

// FILE: a/SuperClass.java
package a;
public class SuperClass {
    protected void superFunction() {}
}

// FILE: b/ChildClass.java
package b;
public class ChildClass extends SuperClass {
    void testFunction() {
        ((SuperClass) new ChildClass()).superFunction(); // ERROR: superFunction() has protected access in a.SuperClass
    }
}

"" : https://youtrack.jetbrains.com/issue/KT-21048

+2

.

subChild.m(), Abstr , protected .

,

    abstract class ParentCl {
        protected var num = 1
        protected open fun m(){
        }
    }

    class ChildCl : ParentCl() {
        private val a0 : ParentCl = ChildCl()
        override fun m() {
            super.m() // 1-st case
            num = 2 // 2-nd case            
            a0.m() // 3-rd case
        }
    }
  • protected ParentCl fun . .
  • protected . .
  • protected fun . .

:

  • m() ParentCl, protected internal public.
  • m() , : private val subChild = Child().

: , m() ParentCl, : public override fun m() {...}

+2

, .

{}, .

abstract class Abstr{
    protected abstract fun m()
}

class Child : Abstr(){
    private val subChild: Abstr = Child()

    override fun m() {
        subChild.m() // Compiles fine
    }
}

https://discuss.kotlinlang.org/

Slack http://slack.kotlinlang.org/

0

All Articles