Getting a random element from a list of elements in Scala

Summary: This tutorial shows how to create a function that returns a random element from a list (or sequence) of input elements. I start by showing how to write a function that works with a Seq[String], and then show how to make the function more generic so that it works with a Seq[A], i.e., a sequence of any data type.

Discussion

In working on projects like SARAH and other apps where I try to make a computer seem more “human,” I’ve been making my software reply to me in random ways. What I’ve found is that this ends up being an easily repeatable pattern, where you have a list of possible replies, and then you randomly return one of those replies.

Getting a random element from a list

The Scala code to implement this “random element from a list” pattern works as follows. First, import the Scala Random class:

import scala.util.Random

Next, create a new random variable in your code:

val random = new Random

Next, create your list/sequence of possible values. For example, I use the following list of possible replies when I say “Computer” to SARAH:

val possibleRepliesToComputer = Seq(
    "Yo",
    "Hello",
    "Hello, Al",
    "What's up?",
    "Como estas?",
    "You rang?",
    "Dude"
)

I get a random string from that list of strings using this code:

val reply = possibleRepliesToComputer(
    random.nextInt(possibleRepliesToComputer.length)
)

That code does what I want, selecting a random element from the list of elements. Using the list size inside the random.nextInt call limits the random value to be within the list/array/sequence size.

Making this a generic function

Of course when something is repeatable like this it screams out to be made into a function, so a simple function will look like this:

def getRandomElement(seq: Seq[String], random: Random): String = 
    seq(random.nextInt(seq.length))

More generically that function can be written like this:

def getRandomElement[A](seq: Seq[A], random: Random): A = 
    seq(random.nextInt(seq.length))

(That’s actually a method, not a function, but I prefer to use the name “function,” especially since they are generally interchangeable in Scala.)

That function can be made better in a variety of ways, but I’ll leave that as an exercise for the reader; I just want to show the general pattern in this article. (To be clear, this function is not a good example of functional programming, because you can’t predict what the function will return based on its inputs.)

In summary, if you wanted to see how to get a random element from a list of elements in Scala (or Java), I hope this has been helpful.