import kotlin.math.min // This import is not strictly necessary for array methods but is kept from the original code.
/**
* A class demonstrating fundamental and advanced operations on Kotlin Arrays.
*/
class arrayexp{
/**
* Demonstrates fundamental array operations: declaration with mixed types,
* indexed access, element modification, size retrieval, element existence check,
* and basic iteration.
*/
fun arr0(){
// Array declaration using the 'arrayOf' factory function.
// Since it contains String and Int, the inferred type is Array<Any>.
var cars = arrayOf("BMW", 2025, "Toyota", 20)
// Accessing elements using the index operator [] and explicitly converting
// all elements to String for print concatenation.
println(cars[0].toString() + " " + cars[1].toString() + " " + cars[2].toString() + " " + cars[3].toString())
// Modifying an element at index 2. Arrays are mutable in size and content.
cars [2] = "Supra"
// Preferred method for printing: using String templates for clear, concise output.
println("${cars[0]} ${cars[1]} ${cars[2]} ${cars[3]}")
// Accessing the 'size' property to get the total number of elements.
println(cars.size)
// Checking for element existence using the idiomatic 'in' operator.
if("Supra" in cars){
println("yes")
}
else{
println("no")
}
// Iterating over all elements using a standard for-in loop.
for(x in cars){
println(x)
}
}
// -------------------------------------------------------------------------------------
/**
* Demonstrates explicit type-specific array creation and various built-in
* extension functions for querying, modifying, and transforming arrays.
*/
fun arr1(){
// Explicitly declaring an Array of type Int.
var nums = arrayOf<Int>(1, 2, 3)
// Explicitly declaring an Array of type String.
var alpha = arrayOf<String>("a", "b", "c")
// Accessing elements using the deprecated 'get' method (prefer the [] operator).
println(nums.get(0))
println(alpha.get(0))
// Utility function to print the array contents in a human-readable format.
println(nums.contentToString())
// Modifying an element using the deprecated 'set' method (prefer the [] operator).
alpha.set(1, "y")
println(alpha.contentToString())
// Retrieving the array size.
println(""+nums.size+" "+alpha.size)
println("${nums.size} ${alpha.size}")
// Retrieving the range of valid indices (0 until size).
println(nums.indices)
println(alpha.indices)
// Boolean check: returns true if the array contains zero elements.
println(nums.isEmpty())
// Boolean check: returns true if the array contains one or more elements.
println(alpha.isNotEmpty())
// Returns true if the element is present.
println(alpha.contains("a"))
// Returns the index of the first matching element, or -1 if not found.
println(alpha.indexOf("a"))
// Returns the index of the last matching element, or -1 if not found.
println(alpha.lastIndexOf("a"))
// Returns the first element matching the predicate (lambda expression).
println(alpha.find { it == "a" })
// Returns the last element matching the predicate.
println(alpha.findLast { it == "a" })
// Sorting: returns a new *List* with elements in ascending order (original array unchanged).
println(alpha.sorted())
// Sorting: returns a new *List* with elements in descending order.
println(alpha.sortedDescending())
// In-place sort: modifies the original array directly (returns Unit, or void).
println(alpha.sort())
// In-place sort: modifies the original array to reverse order (returns Unit).
println(alpha.sortDescending())
// Reversing: returns a new *List* with elements in reverse order.
println(alpha.reversed())
// Summation of numeric elements.
println(nums.sum())
// Calculation of the arithmetic mean.
println(nums.average())
// Retrieving min and max elements. 'minOrNull' and 'maxOrNull' are preferred
// because they safely return null if the array is empty.
// Note: The original functions 'min()' and 'max()' are deprecated.
println("${nums.minOrNull()} ${nums.maxOrNull()}")
// Transformation: converts the array to an immutable List.
println(nums.toList())
// Transformation: converts the array to a Set (removes duplicates).
println(nums.toSet())
}
// -------------------------------------------------------------------------------------
/**
* Demonstrates advanced array creation patterns, including:
* - arrayOfNulls: for creating nullable arrays.
* - emptyArray: for initializing zero-sized arrays (expandable via +=).
* - Array(size) { init }: for creating arrays using an initializer lambda.
*/
fun arr2(){
// Creating an array of 3 nullable String elements, initialized to null.
var aon = arrayOfNulls<String>(3)
println(aon.contentToString())
// Assigning non-null values to the elements.
aon[0] = "A"
aon[1] = "B"
aon[2] = "C"
println(aon.contentToString())
// Using the safe call operator (?.) to call functions (lowercase/uppercase)
// only if the element is not null, preventing NullPointerException.
println("${aon[0]?.lowercase()} ${aon[1]?.uppercase()} ${aon[2]?.lowercase()}")
// Initializing an empty Array of Int.
var ea0 = emptyArray<Int>()
// Appending elements: The '+=' operator creates and assigns a *new* array each time.
// This is inefficient for performance-critical code; lists are better for frequent addition.
ea0 += 10
ea0 += 20
ea0 += 30
println(ea0.size)
println(ea0.contentToString())
// Initializing an empty Array of String and appending elements.
var ea1 = emptyArray<String>()
ea1 += "A"
ea1 += "B"
ea1 += "C"
println(ea1.size)
println(ea1.contentToString())
// Creating an array using the Array constructor with an initializer lambda.
// The lambda's parameter 'i' represents the index (0-4). Value = index + 1.
var numbers = Array(5) { i -> (i + 1)}
println(numbers.contentToString()) // Output: [1, 2, 3, 4, 5]
// Creating an array where the value is the square of the index.
var number = Array(5) { i -> (i * i)}
println(number.contentToString()) // Output: [0, 1, 4, 9, 16]
// Creating an array based on conditional logic within the initializer (i.e., checking parity).
var evenOrodd = Array(5) {i -> if(i % 2 == 0) "even" else "odd"}
println(evenOrodd.contentToString()) // Output: [even, odd, even, odd, even]
}
}
fun main(){
// Instantiates the class
val running = arrayexp()
// Executes the basic array demonstration
running.arr0()
// Executes the advanced array method demonstration
running.arr1()
// Executes the array creation methods demonstration
running.arr2()
}A comprehensive Kotlin demonstration of fundamental and advanced array operations, including creation patterns, element manipulation, and built-in extension functions.
- Overview
- Features
- Getting Started
- Class Structure
- Key Concepts
- Usage Examples
- Best Practices
- Requirements
The arrayexp class provides hands-on demonstrations of Kotlin's array capabilities, from basic operations like declaration and access to advanced techniques such as lambda-based initialization and functional transformations. This code is ideal for learning Kotlin array fundamentals and exploring idiomatic patterns.
- Basic Array Operations: Declaration, indexed access, modification, size retrieval, and iteration
- Type-Specific Arrays: Explicit type declaration for Int, String, and other types
- Built-in Extension Functions: Sorting, searching, transforming, and aggregating arrays
- Advanced Creation Patterns: Nullable arrays, empty arrays, and lambda-based initialization
- Functional Programming: Use of lambda expressions for filtering, mapping, and conditional logic
- Safe Null Handling: Demonstrations of safe call operators and null-safety patterns
- Kotlin 1.3 or later
- A Kotlin compiler or IDE (IntelliJ IDEA, Android Studio, or command line)
- Create a new Kotlin project or file in your IDE
- Copy the code into a
.ktfile - Run the
main()function
kotlinc arrayexp.kt -include-runtime -d arrayexp.jar
java -jar arrayexp.jarDemonstrates core array operations essential for beginners.
Key Operations:
- Declaration: Creating mixed-type arrays with
arrayOf() - Access: Using the index operator
[]and explicit conversions - Modification: Changing element values
- Size Retrieval: Accessing the
sizeproperty - Element Checking: Using the
inoperator for membership testing - Iteration: Looping through arrays with
for-in
Example Output:
BMW 2025 Toyota 20
BMW 2025 Supra 20
4
yes
BMW
2025
Supra
20
Covers explicit type declarations and essential built-in functions.
Key Operations:
- Type-Explicit Declaration: Creating
Array<Int>andArray<String> - Deprecated vs. Current Methods: Comparing
get()/set()with[]operator - Array Queries:
isEmpty(),isNotEmpty(),contains(),indexOf() - Searching:
find(),findLast()with lambda predicates - Sorting:
sorted(),sortedDescending(),sort(),sortDescending(),reversed() - Aggregation:
sum(),average(),minOrNull(),maxOrNull() - Transformations:
toList(),toSet(),contentToString()
Example Output:
1
a
[1, 2, 3]
[a, y, c]
3 3
0..2
0..2
false
true
true
0
0
a
a
[a, y, c]
[c, y, a]
6
2.0
1 3
[1, 2, 3]
[1, 2, 3]
Explores advanced patterns for creating and initializing arrays.
Key Operations:
- Nullable Arrays:
arrayOfNulls<T>()for arrays containing null values - Safe Call Operators: Using
?.to safely access methods on nullable elements - Empty Arrays: Creating expandable arrays with
emptyArray<T>() - Array Constructor with Lambdas:
Array(size) { init }for dynamic initialization - Conditional Logic: Using conditionals inside initializer lambdas
Example Output:
[null, null, null]
[A, B, C]
a B c
3
[10, 20, 30]
3
[A, B, C]
[1, 2, 3, 4, 5]
[0, 1, 4, 9, 16]
[even, odd, even, odd, even]
- Generic Arrays:
Array<T>for any type (object wrapper arrays) - Primitive Arrays:
IntArray,DoubleArray,BooleanArray, etc. (more efficient) - Nullable Arrays:
Array<String?>for arrays that can contain null values
- String Templates: Use
"${variable}"instead of string concatenation - In Operator: Replace
.contains()with theinkeyword for readability - Index Operator: Prefer
array[index]over deprecatedget()andset()methods - Safe Call Operator: Use
?.to safely handle nullable types - Immutable Returns: Functions like
sorted()return Lists, preserving the original array
- Array vs. List: Arrays have fixed size; use Lists for dynamic collections
- In-place Operations: Methods like
sort()andsortDescending()modify the original array - += with Arrays: Creates a new array each time; inefficient for frequent additions
- Primitive Arrays: Use
IntArray,DoubleArray, etc., for better memory efficiency
// Mixed-type array
val data = arrayOf("Name", 25, true)
// Type-specific array
val numbers = arrayOf<Int>(10, 20, 30)
// Nullable array
val optional = arrayOfNulls<String>(5)
// Lambda-based initialization
val squares = Array(5) { i -> i * i }val arr = arrayOf("apple", "banana", "cherry")
// Searching
val item = arr.find { it.length > 5 } // "banana"
// Transforming
val upper = arr.map { it.uppercase() }
// Aggregating
val sizes = arrayOf(10, 20, 30).sum() // 60val nullable = arrayOfNulls<String>(3)
nullable[0] = "Hello"
// Safe call prevents null pointer exceptions
println(nullable[0]?.uppercase()) // "HELLO"
println(nullable[1]?.lowercase()) // null- Prefer
[]Operator: Usearray[index]instead of deprecatedget()andset()methods - Use String Templates: Write
"${var}"instead of concatenation for clarity - Choose Appropriate Types: Use primitive arrays (
IntArray) for primitives andArray<T>for objects - Null Safety: Use
?:or?.let {}for nullable elements - Prefer Lists for Dynamic Collections: Use
ListorMutableListwhen frequent additions/removals are needed - Immutability by Default: Create immutable collections when possible; use
valovervar - Use Extension Functions: Leverage Kotlin's rich set of array functions for cleaner, more expressive code
- Kotlin Version: 1.3 or later
- Dependencies: None (uses Kotlin standard library only)
- Runtime: Java Runtime Environment (JRE) compatible with your Kotlin version
This code is provided as educational material and can be freely used and modified for learning purposes.