Kotlin List toShortArray()
Syntax & Examples


Syntax of List.toShortArray()

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

fun Collection<Short>.toShortArray(): ShortArray

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



✐ Example

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

Summary

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