Home > Net >  Why can't I access some members of an abstract class in this kotlin code?
Why can't I access some members of an abstract class in this kotlin code?

Time:09-23

In the code below I can access all overridden members of the abstract class, but not its own members.


     interface Collection<T: Any> {
        val count: Int
    
        val isEmpty: Boolean
            get() = count == 0
    
           }
    
    
    interface Heap<T: Any> : Collection<T> {
    
        fun peek(): T?
    }
    
    abstract class AbstractHeap<T: Any>() : Heap<T> {
       
        var elements: ArrayList<T> = ArrayList<T>()
    
        override val count: Int
            get() = elements.size
    
        override fun peek(): T? = elements.firstOrNull()
    ...
    }
    class ComparableHeapImpl<T : Comparable<T>> :
        AbstractHeap<T>() {
    
        companion object {
            fun <T : Comparable<T>> create(
                elements: ArrayList<T>
            ): Heap<T> {
                val heap = ComparableHeapImpl<T>()
                heap.heapify(elements)
                return heap
            }
        }
    
    }

I cannot access elements as below


    fun main() {
        val array = arrayListOf(1, 12, 3, 4, 1, 6, 8, 7)
        val test = ComparableHeapImpl.create(array)


        val a = test.elements[0]  // This won't work.
    

}

But in this code I wrote:


    abstract class Test{
        val i = 1
        fun test(){ println("nothing")}
    }
    class Test1: Test(){
        companion object {
            val a = Test1()
            fun create(): Test1 = a
        }
    }


fun main() {
val test = Test1.create()

    test.test() // This works fine.
    println(test.i) // And this works fine.


}

Everything works fine. I cannot make sense of this. Oh, and I am using android studio arctic firefox patch 2.

CodePudding user response:

Your test variable here:

val test = ComparableHeapImpl.create(array)

is not of type AbstractHeap<Int>, it is of type Heap<Int> (by definition of ComparableHeapImpl.create). This is why you cannot access elements - it's not part of the Heap interface.

If you want to access the elements variable, you have several options:

  1. make it part of the Heap interface
  2. make create return AbstractHeap (or ComparableHeapImpl, which would be more logical for this factory function)
  3. cast test to AbstractHeap or ComparableHeapImpl

Why do you want to access this property from outside, though? IMO, you should provide all the public methods/properties that make sense for the usage of your heaps in the Heap interface, but this one most likely should be private (or maybe protected).

  • Related