How to create a generic method in Scala

1 Answer

0 votes
// You create a generic method in Scala by adding a type parameter in square 
// brackets (e.g., [A]) before the method’s parameter list. This allows the 
// method to operate on values of any type while preserving compile‑time type safety

object GenericMethodExample {

  // Generic method
  def printValue[A](value: A): Unit = {
    println(value)
  }

  // Another generic method: return a random element from a sequence
  def randomElement[A](seq: Seq[A]): A = {
    val index = util.Random.nextInt(seq.length)
    seq(index)
  }

  def main(args: Array[String]): Unit = {
    // Using the generic print method
    printValue(123)
    printValue("Scala Generics")
    printValue(3.14)

    // Using the generic randomElement method
    println(randomElement(Seq("Emma", "Amelia", "Sophia")))
    println(randomElement(Seq(1, 2, 3, 4, 5)))
  }
}



/*
run:

123
Scala Generics
3.14
Emma
1

*/

 



answered Apr 22 by avibootz
...