Functions: Generic Input Parameters

When you create a Scala function, you can declare that it uses generic input parameters.

Until now we have just used specific parameter types like Int, String, Boolean, etc., but you can also specify a parameter to be generic, meaning that it can be any type.

Note: This is an introductory example. There are more things you can do with generics, and I’ll show that in the Advanced Scala course.


Start by declaring that a function takes a parameter whose type is Seq[String]:

def randomName(names: Seq[String]): String =
    val randomNum = util.Random.nextInt(names.length)

val names = Seq("Aleka", "Christina", "Tyler", "Molly")
val winner = randomName(names)

And when you look at the function body, notice that there is nothing in the algorithm that uses the String inside the Seq. Therefore, the type doesn’t have to be String, and we can declare it with a generic placeholder:

def randomElement[A](names: Seq[A]): A =
    val seqLength = names.length
    val randomNum = util.Random.nextInt(seqLength)

Now the function can be used with a Seq[String], Seq[Int], Seq[Double], Seq[Boolean], etc.:

@main def generics =

    val names = Seq("Bert", "Ernie", "Grover", "Oscar")
    val winner = randomElement(names)

    val nums = (1 to 100).toVector
    val randomNum = randomElement(nums)

Using generics like this makes your function more general, and useful to more developers and in more situations.