https://kotlinlang.org logo
#announcements
Title
# announcements
a

Ashutosh Panda

11/05/2019, 2:39 AM
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

Mike

11/05/2019, 2:51 AM
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

Ashutosh Panda

11/05/2019, 3:14 AM
Is there any way of assigning size of array at runtime and is there any concept of pointer in kotlin
m

Mike

11/05/2019, 3:38 AM
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

Ashutosh Panda

11/05/2019, 3:39 AM
Ok
m

Mike

11/05/2019, 3:40 AM
Jvm doesn't have pointers in same way C does, but does have powerful collections and processing.
m

molikuner

11/05/2019, 8:56 AM
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

Burkhard

11/05/2019, 10:37 AM
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

molikuner

11/05/2019, 12:16 PM
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

Mike

11/05/2019, 1:02 PM
@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.
4 Views