Hey folks, this is fairly small and succint but wa...
# announcements
g
Hey folks, this is fairly small and succint but was wondering if there was a "nicer"/more kotlinesque way of doing it?
Copy code
val avatarList = mutableListOf<Int>(1,2,3)

fun generateRandomAvatar(): Int? {
	val pick = avatarList.randomOrNull()
	if (pick !== null) avatarList.remove(pick)
	return pick
}
a
I would make the
generateRandomAvatar
receive a
MutableList
.
Unless the whole code you posted is in a dedicated class.
g
@appasni yeh it's in it's own file
a
A quick one to avoid two accesses in list :
Copy code
kotlin
fun <T> MutableList<T>.removeRandomOrNull() : T? {
    return if (isEmpty()) null;
    else removeAt(random().nextInt(0, size))
}
g
Ah that's a good idea, add an extension, thanks @Alexis Manin
And this we can change the function to just
Copy code
fun generateRandomAvatar() = avatarList.removeRandomOrNull()
👍 1
y
You can also change the original to be a one-liner:
Copy code
val avatarList = mutableListOf<Int>(1,2,3)
fun generateRandomAvatar(): Int? = avatarList.randomOrNull()?.also { avatarList.remove(it) }
1
🙌 1
n
instead of
random().nextInt(0, size)
you could also use
indices.random()
. However, I like the
.also
approach best