Kotlin - How to create the function "mutableListOf()"

58 Views Asked by At

Is there a way to create my own dynamic List with out using mutableListOf()? Cause in c++ we use pointers, while in Kotlin i think we cant :(

I searched in diferents sites and i only found how to use the function, not how was it created :(

1

There are 1 best solutions below

0
Joffrey On

mutableListOf() is just a shorthand to create an instance of MutableList, optionally passing some arguments that will be placed in the list upon creation. The 0-arg version of the function is extremely simple and creates an ArrayList:

fun <T> mutableListOf(): MutableList<T> = ArrayList()

You can of course just create instances of lists yourself, by simply instantiating some implementation of the MutableList interface. For instance, on the JVM, you can create an instance of ArrayList or LinkedList by simply calling their constructor:

val myList = ArrayList<String>() // creates a new empty ArrayList<String>

You can also define your own list implementation by creating a class that implements the MutableList interface:

class MyList<T> : MutableList<T> {

    // implement MutableList methods here
}

And then you would create instances of it by calling its constructor:

val myList = MyList<String>()

Cause in c++ we use pointers, while in Kotlin i think we cant :(

You cannot use pointer arithmetic in Kotlin (or other JVM languages), but you don't really have to.