Add sample for setOf method

Ilya Gorbunov: Improve sample to illustrate stable iteration order and set equality.
This commit is contained in:
Swapnil Sankla
2018-01-14 20:53:02 +05:30
committed by Ilya Gorbunov
parent c5aed06110
commit b93e385181
2 changed files with 14 additions and 0 deletions
@@ -271,6 +271,19 @@ class Collections {
assertTrue(set == other, "Empty sets are equal")
assertPrints(set, "[]")
}
@Sample
fun readOnlySet() {
val set1 = setOf(1, 2, 3)
val set2 = setOf(3, 2, 1)
// setOf preserves the iteration order of elements
assertPrints(set1, "[1, 2, 3]")
assertPrints(set2, "[3, 2, 1]")
// but the sets with the same elements are equal no matter of order
assertTrue(set1 == set2)
}
}
class Transformations {
@@ -31,6 +31,7 @@ public fun <T> emptySet(): Set<T> = EmptySet
* Returns a new read-only set with the given elements.
* Elements of the set are iterated in the order they were specified.
* The returned set is serializable (JVM).
* @sample samples.collections.Collections.Sets.readOnlySet
*/
public fun <T> setOf(vararg elements: T): Set<T> = if (elements.size > 0) elements.toSet() else emptySet()