Kotlin Set toShortArray()
Syntax & Examples
Set.toShortArray() extension function
The toShortArray() extension function in Kotlin returns an array of Short containing all of the elements of the collection.
Syntax of Set.toShortArray()
The syntax of Set.toShortArray() extension function is:
fun Collection<Short>.toShortArray(): ShortArray
This toShortArray() extension function of Set returns an array of Short containing all of the elements of this collection.
Return Type
Set.toShortArray() returns value of type ShortArray
.
✐ Examples
1 Converting a set of Short values to a ShortArray
Using toShortArray() to convert a set of Short values to a ShortArray.
For example,
- Create a set of Short values.
- Use toShortArray() to convert the set to a ShortArray.
- Print the resulting array.
Kotlin Program
fun main() {
val shortSet = setOf<Short>(1, 2, 3)
val shortArray = shortSet.toShortArray()
println(shortArray.joinToString())
}
Output
1, 2, 3
2 Handling an empty set of Short values
Using toShortArray() to handle an empty set of Short values.
For example,
- Create an empty set of Short values.
- Use toShortArray() to convert the empty set to a ShortArray.
- Print the resulting array.
Kotlin Program
fun main() {
val emptySet = emptySet<Short>()
val shortArray = emptySet.toShortArray()
println(shortArray.joinToString())
}
Output
3 Converting a set of mixed Short values to a ShortArray
Using toShortArray() to convert a set of mixed Short values to a ShortArray.
For example,
- Create a set of mixed Short values.
- Use toShortArray() to convert the set to a ShortArray.
- Print the resulting array.
Kotlin Program
fun main() {
val mixedSet = setOf<Short>(1, -2, 3, -4)
val shortArray = mixedSet.toShortArray()
println(shortArray.joinToString())
}
Output
1, -2, 3, -4
Summary
In this Kotlin tutorial, we learned about toShortArray() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.