Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Arrays in Kotlin

Arrays in Kotlin

📌 Arrays in Kotlin

In Kotlin, an Array is a collection of fixed-size, ordered data of the same type. Arrays are widely used to store multiple values in a single variable.


✅ Creating Arrays in Kotlin

1. Using arrayOf()

kotlin

val intArray = intArrayOf(1, 2, 3)val doubleArray = doubleArrayOf(1.1, 2.2, 3.3)val charArray = charArrayOf('A', 'B', 'C')

3. Using Array Constructor

kotlin

// Creates an array of size 5 with values as the index multiplied by 2val array = Array(5) { it * 2 }println(array.joinToString()) // Output: 0, 2, 4, 6, 8


✅ Accessing Elements in an Array

You can access array elements using:

  • Indexing: (Starts from 0)

  • get() and set() functions

kotlin

val fruits = arrayOf("Apple", "Banana", "Cherry")// Using Indexprintln(fruits[1]) // Output: Banana// Using get() functionprintln(fruits.get(2)) // Output: Cherry// Updating value using set() functionfruits.set(1, "Mango")println(fruits[1]) // Output: Mango


✅ Array Properties and Functions

  • size → Returns the number of elements in the array.

  • first() → Returns the first element.

  • last() → Returns the last element.

  • contains() → Checks if an element exists in the array.

  • indexOf() → Returns the index of an element or -1 if not found.

kotlin

val numbers = arrayOf(10, 20, 30, 40, 50)println("Size: ${numbers.size}") val names = arrayOf("John", "Emma", "Alex")for (name in names) { println(name)}

2. Using forEach

kotlin

names.forEach { println(it) }

3. Using Indices

kotlin

for (index in names.indices) { println("Index $index: ${names[index]}")}


✅ Multidimensional Arrays

Kotlin supports 2D and 3D Arrays using the Array class.

kotlin

// 2D Array (3x3 Matrix)val matrix = Array(3) { Array(3) { 0 } }matrix[0][1] = 5println(matrix[0][1]) // Output: 5


✅ Conclusion

  • Use arrayOf() for general-purpose arrays.

  • Use intArrayOf(), charArrayOf(), etc., for primitive types.

  • Arrays are fixed in size and cannot be resized. For dynamic collections, use Lists instead.

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql