Composition
andThen et compose
Composition est une leçon Scala for Backend Engineering & Functional Programming gratuite sur CoddyKit. Ceci est la leçon 3 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Scala for Backend Engineering & Functional Programming, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Scala for Backend Engineering & Functional Programming comprend 4 leçons au total.
Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.
Combining functions
Function composition means building a new function by connecting two existing ones, so the output of one becomes the input of the next. Scala provides andThen and compose for this.
object Main {
def main(args: Array[String]): Unit = {
val addOne = (x: Int) => x + 1
val double = (x: Int) => x * 2
val both = addOne andThen double
println(both(5))
}
}andThen: left to right
f andThen g runs f first, then g. Reading left to right matches the order of execution, which many find intuitive.
(f andThen g)(x) == g(f(x))
object Main {
def main(args: Array[String]): Unit = {
val addOne = (x: Int) => x + 1
val triple = (x: Int) => x * 3
val pipeline = addOne andThen triple
println(pipeline(4)) // (4 + 1) * 3
}
}compose: right to left
f compose g runs g first, then f, the mathematical order f(g(x)).
(f compose g)(x) == f(g(x))
object Main {
def main(args: Array[String]): Unit = {
val addOne = (x: Int) => x + 1
val triple = (x: Int) => x * 3
val pipeline = addOne compose triple
println(pipeline(4)) // (4 * 3) + 1
}
}andThen vs compose
The two are mirror images:
f andThen g=g compose ff compose g=g andThen f
Pick whichever reads more naturally for your situation.
object Main {
def main(args: Array[String]): Unit = {
val f = (x: Int) => x + 10
val g = (x: Int) => x * 2
println((f andThen g)(3))
println((g compose f)(3))
}
}Chaining several functions
You can chain many functions with repeated andThen to build a longer pipeline that flows top to bottom.
object Main {
def main(args: Array[String]): Unit = {
val clean = (s: String) => s.trim
val lower = (s: String) => s.toLowerCase
val bang = (s: String) => s + "!"
val process = clean andThen lower andThen bang
println(process(" HELLO "))
}
}Composition changes types
The composed functions need compatible types: the output type of the first must match the input type of the second. The pipeline can change types along the way.
object Main {
def main(args: Array[String]): Unit = {
val length = (s: String) => s.length
val isLong = (n: Int) => n > 5
val check = length andThen isLong
println(check("scala"))
println(check("functional"))
}
}The identity function
identity returns its input unchanged. It is the neutral element of composition: f andThen identity == f. Useful as a default in folds and conditionals.
object Main {
def main(args: Array[String]): Unit = {
val f = (x: Int) => x * 2
val same = f andThen identity[Int]
println(same(7))
}
}Composing with reduce
Since functions are values, you can store several in a list and compose them all using reduce with andThen.
object Main {
def main(args: Array[String]): Unit = {
val steps: List[Int => Int] = List(_ + 1, _ * 2, _ - 3)
val pipeline = steps.reduce(_ andThen _)
println(pipeline(5)) // ((5+1)*2)-3
}
}Building reusable pipelines
Composition encourages small, single-purpose functions that you assemble into larger behavior, a key idea in functional programming.
object Main {
def main(args: Array[String]): Unit = {
val sanitize = (s: String) => s.trim.toLowerCase
val capitalize = (s: String) => s.capitalize
val format = sanitize andThen capitalize
println(format(" aLiCe "))
}
}Composition with map
A composed function is just a function, so you can pass it straight to map to apply the whole pipeline across a collection.
object Main {
def main(args: Array[String]): Unit = {
val transform = ((x: Int) => x + 1) andThen ((x: Int) => x * x)
println(List(1, 2, 3).map(transform))
}
}Reading composition order carefully
A common bug is confusing andThen and compose. Always remember: andThen = first this, then that; compose = the reverse.
object Main {
def main(args: Array[String]): Unit = {
val inc = (x: Int) => x + 1
val sqr = (x: Int) => x * x
println((inc andThen sqr)(2)) // (2+1)^2 = 9
println((inc compose sqr)(2)) // (2^2)+1 = 5
}
}Quick Check
Given f and g, what does (f andThen g)(x) compute?
Recap
You learned function composition:
f andThen g→g(f(x))(left to right)f compose g→f(g(x))(right to left)- They are mirror images of each other
identityis the neutral element- Compose lists of functions with
reduce(_ andThen _)
Questions Fréquemment Posées
La leçon « Composition » est-elle gratuite ?
Oui — le texte complet de « Composition » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Scala for Backend Engineering & Functional Programming, passe à CoddyKit PRO. Le cours Scala for Backend Engineering & Functional Programming comprend 4 leçons au total.
Qu'est-ce que j'apprendrai dans « Composition » ?
andThen et compose Tu pratiques Scala for Backend Engineering & Functional Programming avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.
Dois-je avoir de l'expérience pour commencer Scala for Backend Engineering & Functional Programming ?
Aucune expérience préalable n'est requise. Scala for Backend Engineering & Functional Programming sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 3 sur 4.
Combien de temps prend la leçon « Composition » ?
La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.
Peux-tu écrire et exécuter du code dans cette leçon Scala for Backend Engineering & Functional Programming ?
Oui. Chaque leçon Scala for Backend Engineering & Functional Programming inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.