Kotlin Array copyOfRange Function

The copyOfRange function in Kotlin is used to create a new array that is a copy of a specified range of elements from an existing array. This function is part of the Kotlin standard library and provides a straightforward way to duplicate a portion of an array.

Table of Contents

  1. Introduction
  2. copyOfRange Function Syntax
  3. Understanding copyOfRange
  4. Examples
    • Basic Usage
    • Using copyOfRange with Custom Types
    • Handling Out of Bounds
  5. Real-World Use Case
  6. Conclusion

Introduction

The copyOfRange function creates a new array that contains elements from the specified range of the original array. This is useful for creating subarrays or slices of the original array.

copyOfRange Function Syntax

The syntax for the copyOfRange function is as follows:

fun <T> Array<out T>.copyOfRange(fromIndex: Int, toIndex: Int): Array<T>

Parameters:

  • fromIndex: The start index (inclusive) of the range to copy.
  • toIndex: The end index (exclusive) of the range to copy.

Returns:

  • A new array containing the elements from the specified range of the original array.

Understanding copyOfRange

The copyOfRange function creates a new array that includes elements from the original array starting at fromIndex and ending at toIndex - 1. The new array will have a size equal to toIndex - fromIndex.

Examples

Basic Usage

To demonstrate the basic usage of copyOfRange, we will create an array of integers and copy a range of elements to a new array.

Example

fun main() {
    val numbers = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9)
    val subArray = numbers.copyOfRange(2, 5)
    println("Original array: ${numbers.joinToString()}")
    println("Subarray: ${subArray.joinToString()}")
}

Output:

Original array: 1, 2, 3, 4, 5, 6, 7, 8, 9
Subarray: 3, 4, 5

Using copyOfRange with Custom Types

This example shows how to use copyOfRange with an array of custom objects.

Example

data class Person(val name: String, val age: Int)

fun main() {
    val people = arrayOf(
        Person("Ravi", 25),
        Person("Anjali", 30),
        Person("Priya", 22),
        Person("Rahul", 28),
        Person("Amit", 35)
    )

    val subArray = people.copyOfRange(1, 4)
    println("Original array: ${people.joinToString()}")
    println("Subarray: ${subArray.joinToString()}")
}

Output:

Original array: Person(name='Ravi', age=25), Person(name='Anjali', age=30), Person(name='Priya', age=22), Person(name='Rahul', age=28), Person(name='Amit', age=35)
Subarray: Person(name='Anjali', age=30), Person(name='Priya', age=22), Person(name='Rahul', age=28)

Handling Out of Bounds

This example demonstrates how to handle cases where the specified range is out of bounds.

Example

fun main() {
    val numbers = arrayOf(1, 2, 3, 4, 5)
    try {
        val subArray = numbers.copyOfRange(3, 8)
        println("Subarray: ${subArray.joinToString()}")
    } catch (e: ArrayIndexOutOfBoundsException) {
        println("Error: ${e.message}")
    }
}

Output:

Error: end index (8) is greater than array length (5).

Real-World Use Case

Extracting a Subarray for Processing

In real-world applications, the copyOfRange function can be used to extract a subarray for further processing, such as extracting a subset of data points for analysis.

Example

fun main() {
    val dataPoints = arrayOf(10.5, 20.3, 30.7, 40.2, 50.1, 60.8, 70.6)
    val subset = dataPoints.copyOfRange(2, 5)

    // Perform analysis on the subset
    val average = subset.average()
    println("Subset: ${subset.joinToString()}")
    println("Average of subset: $average")
}

Output:

Subset: 30.7, 40.2, 50.1
Average of subset: 40.333333333333336

Conclusion

The copyOfRange function in Kotlin is a convenient method for creating a new array that is a copy of a specified range of elements from an existing array. It provides a simple way to extract subarrays and handle cases where resizing or slicing is needed. 

By understanding and using this function, you can effectively manage array slicing and duplication operations in your Kotlin applications.

Comments