Search code examples
listcollectionsinterfacekotlinabstract-class

How can I implement Collection/List interface or abstract class in Kotlin?


I'm having trouble implementing the iterator and get set functions. (Edit: By trouble I mean that I don't know how to do it and I need help)

In the past, I've inherited from ArrayList even though I need a fixed-size collection. I've also used an Array property in my class and added a get and a set operator funcions, but these two solutions just feel like unnecessary workarounds.

Edit: I just found out that Kotlin itself doesn't have a List implementation yet (it uses ArrayList instead), So maybe I'm not supposed to be able to Implement it. I'm going to keep this open just in case.


Solution

  • There is a very neat feature in Kotlin that allows you to easily implement the List interface by Delegation. Just use the by operator on a list property, then the class will delegate all methods of the List interface to that property. So, for example, instead of,

    class Cars {
        private val cars = ArrayList<Car>()
    }
    

    you write:

    class Cars(
        private val cars: MutableList<Car> = ArrayList<Car>()
    ): MutableList<Car> by cars
    

    Now Cars implements List, and can be used just as such:

    val cars = Cars()
    cars.add(Car())
    for (car in cars)
        car.vroom()