Search code examples
functionscalafunctional-programmingcomposition

Where and why is identity function useful?


I understand why function composition is important. It allows building large and complex functions from small and simple ones.

val f: A => B = ...
val g: B => C = ...

val h = f andThen g; // compose f and g

This composition conforms to identity and associativity laws.

Associativity is useful because it allows grouping f1 andThen f2 andThen f3 andThen f4 ... in any order. Now I wonder why identity is useful.

def f[T](t:T) = t   // identity function
val g: A => B = ... // just any function
g andThen f[B] == f[A] andThen g 

So, my question is where and why this identity useful.


Solution

  • Identity is useful whenever an interface gives you more control than you actually need. For example, Either has no flatten method. Let's suppose you have

    val e: Either[Double, Float] = Right(1.0f)
    

    and you want to flatten it to a Double. How do you do it? There is a handy fold method, but no method to convert the right side to the left side's type. So you

    e.fold(identity, _.toDouble)
    

    and you've got what you want.