Kotlin Set toLongArray()
Syntax & Examples


Set.toLongArray() extension function

The toLongArray() extension function in Kotlin returns an array of Long containing all of the elements of the collection.


Syntax of Set.toLongArray()

The syntax of Set.toLongArray() extension function is:

fun Collection<Long>.toLongArray(): LongArray

This toLongArray() extension function of Set returns an array of Long containing all of the elements of this collection.

Return Type

Set.toLongArray() returns value of type LongArray.



✐ Examples

1 Converting a set of Long values to a LongArray

Using toLongArray() to convert a set of Long values to a LongArray.

For example,

  1. Create a set of Long values.
  2. Use toLongArray() to convert the set to a LongArray.
  3. Print the resulting array.

Kotlin Program

fun main() {
    val longSet = setOf(1L, 2L, 3L)
    val longArray = longSet.toLongArray()
    println(longArray.joinToString())
}

Output

1, 2, 3

2 Handling an empty set of Long values

Using toLongArray() to handle an empty set of Long values.

For example,

  1. Create an empty set of Long values.
  2. Use toLongArray() to convert the empty set to a LongArray.
  3. Print the resulting array.

Kotlin Program

fun main() {
    val emptySet = emptySet<Long>()
    val longArray = emptySet.toLongArray()
    println(longArray.joinToString())
}

Output


3 Converting a set of mixed Long values to a LongArray

Using toLongArray() to convert a set of mixed Long values to a LongArray.

For example,

  1. Create a set of mixed Long values.
  2. Use toLongArray() to convert the set to a LongArray.
  3. Print the resulting array.

Kotlin Program

fun main() {
    val mixedSet = setOf(1L, -2L, 3L, -4L)
    val longArray = mixedSet.toLongArray()
    println(longArray.joinToString())
}

Output

1, -2, 3, -4

Summary

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