Sounds like you have a collection of functions and you just need to use a HashMap. i would be index of the map. Hashmaps are useful because they find the corresponding value for a key quickly, without having to compare lots of values until a match is found.
Here is an example of a HashMap from Any to Any => Any. Because Scala supports tuples, this is a completely general solution.
object Hello extends App { import scala.collection.immutable type F1 = (Any) => Any val hashMap: immutable.Map[Int, F1] = immutable.HashMap[Int, F1]( 1 -> { (a: Int) => a * 2 }.asInstanceOf[F1], // Function literal that doubles it's input 2 -> { (tuple: (String, Int)) => tuple._1 * tuple._2 }.asInstanceOf[F1], // Function literal that repeats the string 1000 -> { (_: Unit) => s"The date and time is ${ new java.util.Date() }" }.asInstanceOf[F1] ) def lookup(i: Int, args: Any): Any = hashMap(i)(args) def report(i: Int, args: Any): Unit = println(s"$i: ${ lookup(i, args) }") report(1, 21) report(2, ("word ", 5)) report(1000, ()) }
Here is the output:
1: 42 2: word word word word word 1000: The date and time is Sat Dec 23 19:45:56 PST 2017
Update: Here is a version that uses an array. Notice that the indices must start at 0 for this version, not an arbitrary number as before:
object Hello2 extends App { type F1 = (Any) => Any val array: Array[F1] = Array[F1]( { (a: Int) => a * 2 }.asInstanceOf[F1], // Function literal that doubles it's input { (tuple: (String, Int)) => tuple._1 * tuple._2 }.asInstanceOf[F1], // Function literal that repeats the string { (_: Unit) => s"The date and time is ${ new java.util.Date() }" }.asInstanceOf[F1] ) def lookup(i: Int, args: Any): Any = array(i)(args) def report(i: Int, args: Any): Unit = println(s"$i: ${ lookup(i, args) }") report(0, 21) report(1, ("word ", 5)) report(2, ()) }
Output is:
0: 42 1: word word word word word 2: The date and time is Sat Dec 23 20:32:33 PST 2017
switchstatement.switchstatements with 1000 cases don't compile toif-elsechains.