Kotlin Array.toUByteArray()

Kotlin Array.toUByteArray() Tutorial

The Array.toUByteArray() function in Kotlin is used to convert an Array of UByte type values, into a UByteArray. It creates a new UByteArray containing the elements of the original array.

This is just a conversion of data from Array<UByte> type to UByteArray type.

This tutorial will explore the syntax of the Array.toUByteArray() function and provide examples of its usage in Kotlin arrays.

Syntax

The syntax of the Array.toUByteArray() function is as follows:

fun Array<out UByte>.toUByteArray(): UByteArray

Examples for Array.toUByteArray() function

1. Convert Array of unsigned bytes to UByteArray

In this example, we’ll take an array of unsigned bytes, and convert this Array into a UByteArray using Array.toUByteArray().

Kotlin Program

fun main() {
    val originalArray: Array<UByte> = arrayOf(130U, 10U, 48U)

    // Using toUByteArray() to convert the Array of unsigned bytes to a UByteArray
    val ubyteArray = originalArray.toUByteArray()

    // Printing the original array and the resulting ubyte array
    println("Given Array:\n${originalArray.contentToString()}\n")
    println("UByte Array:\n${ubyteArray.contentToString()}")
}

Output

Given Array:
[130, 10, 48]

UByte Array:
[130, 10, 48]

Summary

In this tutorial, we’ve covered the Array.toUByteArray() function in Kotlin, its syntax, and how to use it to convert an Array of UByte values into a UByteArray.