Extension random() to select random element from a collection

Fixes #KT-15539
This commit is contained in:
Ilya Gorbunov
2018-08-24 06:12:50 +03:00
parent b0bcd78e38
commit ea2c33a532
20 changed files with 652 additions and 3 deletions
@@ -16,6 +16,7 @@ package kotlin.collections
import kotlin.*
import kotlin.text.*
import kotlin.comparisons.*
import kotlin.random.*
/**
* Returns 1st *element* from the collection.
@@ -456,6 +457,29 @@ public inline fun <T> List<T>.lastOrNull(predicate: (T) -> Boolean): T? {
return null
}
/**
* Returns a random element from this collection.
*
* @throws NoSuchElementException if this collection is empty.
*/
@SinceKotlin("1.3")
@kotlin.internal.InlineOnly
public inline fun <T> Collection<T>.random(): T {
return random(Random)
}
/**
* Returns a random element from this collection using the specified source of randomness.
*
* @throws NoSuchElementException if this collection is empty.
*/
@SinceKotlin("1.3")
public fun <T> Collection<T>.random(random: Random): T {
if (isEmpty())
throw NoSuchElementException("Collection is empty.")
return elementAt(random.nextInt(size))
}
/**
* Returns the single element, or throws an exception if the collection is empty or has more than one element.
*/