如何在Kotlin中将Set(HashSet)转换为Array?

Ani*_*bla 1 arrays set hashset kotlin

我有一套String

 val set = HashSet<String>()
    set.add("a")
    set.add("b")
    set.add("c")
Run Code Online (Sandbox Code Playgroud)

我需要将其转换为数组

val array = arrayOf("a", "b", "c")
Run Code Online (Sandbox Code Playgroud)

Abn*_*cio 8

使用扩展功能toTypedArray如下

set.toTypedArray()
Run Code Online (Sandbox Code Playgroud)

该功能属于Kotlin图书馆

/**
 * Returns a *typed* array containing all of the elements of this collection.
 *
 * Allocates an array of runtime type `T` having its size equal to the size of this collection
 * and populates the array with the elements of this collection.
 * @sample samples.collections.Collections.Collections.collectionToTypedArray
 */
@Suppress("UNCHECKED_CAST")
public actual inline fun <reified T> Collection<T>.toTypedArray(): Array<T> {
    @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
    val thisCollection = this as java.util.Collection<T>
    return thisCollection.toArray(arrayOfNulls<T>(0)) as Array<T>
}
Run Code Online (Sandbox Code Playgroud)