Understanding polymorphic functions
A function that works with multiple types of input arguments or can return a value of different types is called a polymorphic function. While writing a polymorphic function, we provide a comma-separated list of type parameters surrounded by square brackets after the name of the function. For example, we can write a function that returns the index of the first occurrence of an element within List
:
scala> def findFirstIn[A](as: List[A], p: A => Boolean): Option[Int] = | as.zipWithIndex.collect { case (e, i) if p(e) => i }.headOption findFirstIn: [A](as: List[A], p: A => Boolean)Option[Int] example 1.43
This function will work for any type of list: List[Int]
, List[String]
, and so on. For example, we can search for the index of element 5 in a list of integers from 1 to 20:
scala> import scala.util.Random import scala.util.Random scala> val ints = Random.shuffle((1 to 20).toList) ints: List[Int] = List(7, 9, 3, 8, 6, 13, 12, 18, 14, 15, 1, 11, 10, 16, 2, 5, 20, 17, 4, 19) scala> findFirstIn[Int](ints, _ == 5) res38: Option[Int] = Some(15)
Example 1.44
In the next section, we are going to look at another property of type parameters, called variance, which defines subtyping relationships between objects, as we will see in the following section.