0Pricing
Scala for Backend Engineering & Functional Programming · Leçon

Fonctions comme valeurs

Fonctions de première classe

Fonctions comme valeurs est une leçon Scala for Backend Engineering & Functional Programming gratuite sur CoddyKit. Ceci est la leçon 1 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.

Functions are values

In Scala, functions are first-class values. You can store them in variables, pass them as arguments, and return them from other functions, just like numbers or strings.

object Main {
  def main(args: Array[String]): Unit = {
    val increment: Int => Int = x => x + 1
    println(increment(5))
  }
}

Function type syntax

The type Int => String means a function taking an Int and returning a String. Multiple parameters use parentheses: (Int, Int) => Int.

object Main {
  def main(args: Array[String]): Unit = {
    val add: (Int, Int) => Int = (a, b) => a + b
    val label: Int => String = n => s"value=$n"
    println(add(3, 4))
    println(label(7))
  }
}

Lambda (anonymous function) syntax

An anonymous function, or lambda, is written (params) => body. It has no name and is often passed directly to another function.

object Main {
  def main(args: Array[String]): Unit = {
    val square = (x: Int) => x * x
    println(square(6))
  }
}

Higher-order functions

A higher-order function is one that takes a function as a parameter or returns a function. map and filter are classic examples.

object Main {
  def applyTwice(f: Int => Int, x: Int): Int = f(f(x))
  def main(args: Array[String]): Unit = {
    println(applyTwice(_ + 3, 10))
  }
}

Passing functions to methods

Collection methods accept functions. You can pass a lambda inline or pass a named function value.

object Main {
  def main(args: Array[String]): Unit = {
    val triple = (x: Int) => x * 3
    println(List(1, 2, 3).map(triple))
    println(List(1, 2, 3).map(x => x * 3))
  }
}

Returning functions

A function can return another function. Here multiplier returns a function that multiplies by a fixed factor, a small function factory.

object Main {
  def multiplier(factor: Int): Int => Int = x => x * factor
  def main(args: Array[String]): Unit = {
    val timesTen = multiplier(10)
    println(timesTen(5))
  }
}

Methods vs functions

A def defines a method. You can turn a method into a function value with the eta-expansion underscore: methodName _, or just by using it where a function is expected.

object Main {
  def doubleIt(x: Int): Int = x * 2
  def main(args: Array[String]): Unit = {
    val f: Int => Int = doubleIt
    println(f(8))
    println(List(1, 2, 3).map(doubleIt))
  }
}

Functions with no parameters

A function can take no arguments. Its type is written () => T. This is useful for deferring computation.

object Main {
  def main(args: Array[String]): Unit = {
    val greeting: () => String = () => "Hello!"
    println(greeting())
  }
}

Storing functions in collections

Because functions are values, you can store them in lists or maps and look them up dynamically, building a tiny command dispatcher.

object Main {
  def main(args: Array[String]): Unit = {
    val ops: Map[String, (Int, Int) => Int] = Map(
      "add" -> (_ + _),
      "mul" -> (_ * _)
    )
    println(ops("add")(3, 4))
    println(ops("mul")(3, 4))
  }
}

Functions as configuration

Passing a function lets callers customize behavior. Here a generic transformAll applies any function across a list.

object Main {
  def transformAll(xs: List[Int], f: Int => Int): List[Int] = xs.map(f)
  def main(args: Array[String]): Unit = {
    println(transformAll(List(1, 2, 3), _ + 100))
    println(transformAll(List(1, 2, 3), _ * 10))
  }
}

A cleaner customization example

Here is the same idea written cleanly: callers supply the transformation, keeping the helper generic and reusable.

object Main {
  def transformAll(xs: List[Int], f: Int => Int): List[Int] = xs.map(f)
  def main(args: Array[String]): Unit = {
    println(transformAll(List(1, 2, 3), x => x + 100))
    println(transformAll(List(1, 2, 3), x => x * x))
  }
}

Quick Check

What is a higher-order function?

Recap

You learned that functions are first-class values:

  • Store functions in vals, lists, and maps
  • Function types like Int => String
  • Lambdas: (x) => body and the _ shorthand
  • Higher-order functions take or return functions
  • Methods become function values via eta-expansion

Questions Fréquemment Posées

La leçon « Fonctions comme valeurs » est-elle gratuite ?

Oui — le texte complet de « Fonctions comme valeurs » 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 « Fonctions comme valeurs » ?

Fonctions de première classe 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 1 sur 4.

Combien de temps prend la leçon « Fonctions comme valeurs » ?

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.

Toutes les leçons de ce cours

  1. Fonctions comme valeurs
  2. Curryfication
  3. Composition
  4. Fermetures
← Retour à Scala for Backend Engineering & Functional Programming