-
Notifications
You must be signed in to change notification settings - Fork 0
Arrays
Just like variables, arrays can be created with the keyword val
, or with specific type. If an array will only contain one type of values, it is possible to initialize it with int[]
, float[]
, bool[]
or string[]
.
Important: arrays of undefined type are defined with val
, not val[]
.
val arrayOfValues = [1, "Kode", true, 0.2]
int[] arrayOfInts = [1, 2, 3, 4]
These operations will cause errors:
float[] arrayOfFloats = [1.4, 1.5, "hello"]
string[] arrayOfStrings = "my string is not in an array"
Also like variables, arrays are typed at initialization, which means if an array is created with only one type of values in it, it will automatically become a typed array of that type.
val array = [1,2,3]
print(typeOf(array)) # prints int[]
The length of the array can be found using the len()
function.
val array = ["a", "b", "c"]
print(len(array)) # prints 3
This can be useful in for loops.
To add values to an array, the append(array, element)
function can be used. Append returns the new array and does not modify the original, it must be assigned to it instead.
val myArray = [1, 2, "Fred", "Eduard"]
myArray = append(myArray, "Kode")
After this, myArray contains [1, 2, "Fred", "Eduard", "Kode"]
val myArray = [1, 2, "Fred", "Eduard"]
append(myArray, "Kode")
After this, myArray contains [1, 2, "Fred", "Eduard"]
To remove values from an array, the truncate(array, index)
function can be used. Just like append, truncate returns the modified array.
val myArray = [1, 2, "Fred", "Eduard"]
myArray = truncate(myArray, 0)
After this, myArray contains [2, "Fred", "Eduard"]
At the moment, printing arrays directly is not supported in Kode. If you use print()
with an array as parameter, the program will output array
.