14c. Functions (compose, andThen) - RobertMakyla/scalaWiki GitHub Wiki

Function composition

    def f(s: String) = "f(" + s + ")"

    def g(s: String) = "g(" + s + ")"

compose

     val fComposeG = f _ compose g _

     fComposeG("yay")  // --> f(g(yay))

andThen

     val fAndThenG = f _ andThen g _

     fAndThenG("yay")  // --> g(f(yay))

FUNCTIONS in scala are objects

     val f = (x:Int) => x*x              // if '=>' format, then converted to Function1[Int,Int]

  is the same as

     class AnonFunc extends Function1[Int,Int]{
          def apply(x:Int) = x*x        // if starts with def, then NOT converted to Function1[Int,Int]
     }                                 // to avoid infinite loop, cause then it would also have it's own apply()
                                      // which would be a function with another apply and so on..

     val f = new AnonFunc

  or real anonymous class (skipping class name)

     val f = new Function1[Int,Int]{
           def apply(x:Int) = x*x
     }

  Function1[I,O]  // 1 means that there is one input argument of type I, and output of type O