3.2 Polymorphic functions (abstracting over the type) - Gaoey/scala-diary GitHub Wiki

monomorphic functions or functions that operate on only one type of data.

For example, abs and factorial are specific to arguments of type Int.

especially when writing HOFs, we want to write code that works for any type it’s given. These are called polymorphic functions or we call generic function.

Monomorphic Example - single type

def findFirst(ss: Array[String], key: String): Int = {
    @annotation.tailrec
    def loop(n: Int): Int =
        if (n >= ss.length) -1
        else if (ss(n) == key) n
        else loop(n + 1)

   loop(0)
}

Polymorphic Example - any type

def findFirst[A](as: Array[A], p: A => Boolean): Int = {
    @annotation.tailrec
    def loop(n: Int): Int =
        if (n >= as.length) -1
        else if (p(as(n))) n
        else loop(n + 1)

    loop(0)
}