Kotlin List toUByteArray()
Syntax & Examples


Syntax of List.toUByteArray()

The syntax of List.toUByteArray() extension function is:

fun Collection<UByte>.toUByteArray(): UByteArray

This toUByteArray() extension function of List returns an array of UByte containing all of the elements of this collection.



✐ Examples

1 Example

In this example,

  • We create a list named list1 containing shorts 1, 2, 2, 3, 4, 4, 5.
  • We convert list1 to a ShortArray using the toShortArray() extension function.
  • We print the elements of the shortArray joined into a string to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf(1.toShort(), 2.toShort(), 2.toShort(), 3.toShort(), 4.toShort(), 4.toShort(), 5.toShort())
    val shortArray = list1.toShortArray()
    println(shortArray.joinToString())
}

Output

1, 2, 2, 3, 4, 4, 5

2 Example

In this example,

  • We create a list named list2 containing characters 'a', 'b', 'c', 'c', 'd'.
  • We convert each character in list2 to a Short using map { it.toShort() } and then convert the list to a ShortArray using toShortArray() extension function.
  • We print the elements of the shortArray joined into a string to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val list2 = listOf('a', 'b', 'c', 'c', 'd')
    val shortArray = list2.map { it.toShort() }.toShortArray()
    println(shortArray.joinToString())
}

Output

97, 98, 99, 99, 100

3 Example

In this example,

  • We create a list named list3 containing strings "apple", "banana", "cherry".
  • We map each string in list3 to its length as a Short using map { it.length.toShort() } and then convert the list to a ShortArray using toShortArray() extension function.
  • We print the elements of the shortArray joined into a string to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val list3 = listOf("apple", "banana", "cherry")
    val shortArray = list3.map { it.length.toShort() }.toShortArray()
    println(shortArray.joinToString())
}

Output

5, 6, 6

Summary

In this Kotlin tutorial, we learned about toUByteArray() extension function of List: the syntax and few working examples with output and detailed explanation for each example.