I want to declare an array but do not want to put ...
# announcements
a
I want to declare an array but do not want to put values into it then itself I will enter values later when require , as it happens in other languages , however how should I do it in Kotlin
m
https://kotlinlang.org/docs/reference/basic-types.html#arrays Depends on type of array exactly which one you want. If it's a 'primitive', the
IntArray(10)
will create an Integer Array of size 10, with all elements having value 0.
val stringArray = arrayOfNulls<String>(10)
If you don't want the elements to be nullable, then you can use
val stringArray = Array(10) {""}
That looks 'weird', but basically you're creating an Array of size 10, and initializing all the values with an empty String. This will result in an Array<String> of size 10.
The {""} is a lambda called for each item in the array. It passes the index, but in this case, all elements are the same, so we don't define a variable to hold the index
a
Is there any way of assigning size of array at runtime and is there any concept of pointer in kotlin
m
May I suggest that rather than trying to solve a problem the way you would have in another language, perhaps describe what it is you're tying to accomplish, and we can give you an idiomatic way of doing it in Kotlin.
a
Ok
m
Jvm doesn't have pointers in same way C does, but does have powerful collections and processing.
m
Actually I would suggest switching from arrays to lists. They are even more powerful in kotlin, than they are (for example) in Java. If you don’t need the possibility to change the length at runtime, you can even remove some overhead by creating an ArrayList with specific
initialCapacity
.
Copy code
val list: List<String> = ArrayList<String>(5)
b
initialCapacity
has nothing to do with a fixed size. You can use it even if you want to change the length later.
ArrayList
is backed by an array. If the list is full when you add, a new array is created with a bigger size. The old data is then copied into the new array. Also while I normally would suggest using Lists as well, there is still an argument for arrays if you know you have a fixed length.
💯 1
m
I know, that
initialCapacity
!=
fixed size
, but I just said, that this would remove the overhead of copying the array over and over again, if you now the length in beforehand.
m
@molikuner Unfortunately, your statement would be interpreted as you saying the list would be fixed length if one uses the
initialCapacity
constructor. I agree it's helpful if you know up front what size the list is, or set a large enough initial size before populating it to avoid the churn of constantly growing it.