home search about rss feed twitter ko-fi

Functions: Generic Input Parameters (Scala 3 Video)

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.

Example

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)
    names(randomNum)

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)
    names(randomNum)

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)
    println(winner)

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

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

Update: All of my new videos are now on
LearnScala.dev