Scala: compose, andThen


1) andThen - composes 2 functions from left to right, "execute first and send result into input of seconds function and etc" 
Example: we have 4 functions:
String => Int 
Int => Int
Int => Double
Double => String

we can compose all this function in chain and produce function String => String, look at val func

val StrToInt :String => Int = param => param.toInt

val mult2: Int => Int = param => param*2

val addSmall: Int => Double = param => param+0.1

val DblToString :Double => String = param => param.toString

val initVal:String = "123"

(StrToInt andThen mult2 andThen addSmall andThen DblToString)(initVal)

DblToString(addSmall(mult2(StrToInt(initVal))))

val func : String => String = StrToInt andThen mult2 andThen addSmall andThen DblToString

func(initVal)
Output

StrToInt: String => Int = function

mult2: Int => Int = function

addSmall: Int => Double = function

DblToString: Double => String = function

initVal: String = 123

res0: String = 246.1

res1: String = 246.1

func: String => String = scala.Function1

res2: String = 246.1

andThen and compose defined only for Function1 (function of 1 parameter), not 0 not 2 and more parameters.

trait Function1 ...

  /** Composes two instances of Function1 in a new Function1, with this function applied last.
   */
  def compose[A](g: A => T1): A => R = { x => apply(g(x)) }

  /** Composes two instances of Function1 in a new Function1, with this function applied first.
   */
  def andThen[A](g: R => A): T1 => A = { x => g(apply(x)) }
  

compose is equivalent to andThen but in reverse

val funcComp: String => String = DblToString compose addSmall compose mult2 compose StrToInt

funcComp(initVal)

res2: String = 246.1


Комментарии

Популярные сообщения из этого блога

Spark operations with sparl.sql (Dataset, Dataframe)

Loading data into Spark from Oracle RDBMS, CSV

Load data from Cassandra to HDFS parquet files and select with Hive