Scala 3: An apply/factory method that takes a varargs/tuple parameter

Here’s a brief Scala 3 example that shows how to:

  1. Create a companion object,
  2. Create an apply method in that companion object that acts as a factory method,
  3. Define that apply method to take a varargs tuple parameter, and
  4. Create new Person instances using that factory method.

Here’s the complete source code for this example:

// [1] create a basic class
class Person private(val name: String, val age: Int):
    override def toString = s"$name is $age years old"
   
object Person:
    // [2] create an 'apply' method in the companion object,
    // which is a “factory method” for the class, as you’ll
    // see in the @main method below.
    def apply(t: (String, Int)) = new Person(t(0), t(1))
    // [3] the '(String, Int)*' syntax here means, “Zero or more
    // two-element tuples, where the first element must be
    // a String and the second element must be an Int.”
    def apply(ts: (String, Int)*) =
        for t <- ts yield new Person(t(0), t(1))

@main def applyTupleVarargsTest =

    // [4] create a person using a tuple-2 as the argument
    val john = Person(("Smokey", 30))
    println(john)

    // [5] create multiple people using a variable number 
    // (vararg) of tuples
    val peeps = Person(
        ("Barb", 33),
        ("Cheryl", 31)
    )
    peeps.foreach(println)

If you ever wanted to see how to create an apply method in a companion object to create a factory method — which serves as a constructor for the class — or how to create a tuple as a varargs parameter in Scala, I hope this example is helpful.

If you’re interested in more details, this example comes from the Scala Cookbook, 2nd Edition, which you can now order through that link.