Passer au contenu principal

🔧 Fonctions d'extension

📖 Qu'est-ce qu'une fonction d'extension ?

Une fonction d'extension (Extension Function) est une fonctionnalité qui permet d'ajouter de nouvelles fonctions à une classe existante sans la modifier. Vous pouvez l'utiliser comme si c'était une méthode d'origine !

💡 Utilisation de base

Première fonction d'extension

// Ajouter une nouvelle fonction à String !
fun String.isEmail(): Boolean {
return this.contains("@") && this.contains(".")
}

fun main() {
val email = "hong@example.com"

println(email.isEmail()) // true
println("invalid".isEmail()) // false
}

Propriété d'extension

val String.firstChar: Char
get() = if (this.isNotEmpty()) this[0] else ' '

fun main() {
println("Hello".firstChar) // H
println("Kotlin".firstChar) // K
}

🎯 Exemples pratiques

Utilitaires de chaînes

// Format de numéro de téléphone
fun String.toPhoneFormat(): String {
return if (this.length == 11) {
"${substring(0, 3)}-${substring(3, 7)}-${substring(7)}"
} else {
this
}
}

// Tronquer une chaîne
fun String.truncate(length: Int): String {
return if (this.length > length) {
"${substring(0, length)}..."
} else {
this
}
}

// Extraire uniquement les chiffres
fun String.numbersOnly(): String {
return this.filter { it.isDigit() }
}

fun main() {
println("01012345678".toPhoneFormat()) // 010-1234-5678

val long = "This is a very long text"
println(long.truncate(10)) // This is a ...

println("가격: 1,500원".numbersOnly()) // 1500
}

Utilitaires de nombres

// Vérifier si pair
fun Int.isEven(): Boolean = this % 2 == 0

// Vérifier la plage
fun Int.isBetween(min: Int, max: Int): Boolean {
return this in min..max
}

// Format de devise
fun Int.toCurrency(): String {
return "%,d원".format(this)
}

fun main() {
println(4.isEven()) // true
println(7.isEven()) // false

println(50.isBetween(0, 100)) // true

println(1500000.toCurrency()) // 1,500,000원
}

Utilitaires de collections

// Deuxième élément sécurisé
fun <T> List<T>.secondOrNull(): T? {
return if (this.size >= 2) this[1] else null
}

// Premier index correspondant à la condition
fun <T> List<T>.indexOfFirstOrNull(predicate: (T) -> Boolean): Int? {
val index = this.indexOfFirst(predicate)
return if (index >= 0) index else null
}

// Grouper une liste par n éléments
fun <T> List<T>.chunked(size: Int): List<List<T>> {
return this.chunked(size)
}

fun main() {
val numbers = listOf(1, 2, 3, 4, 5)

println(numbers.secondOrNull()) // 2

val index = numbers.indexOfFirstOrNull { it > 3 }
println(index) // 3 (index)

println(numbers.chunked(2)) // [[1, 2], [3, 4], [5]]
}

Date/Heure (version simple)

data class SimpleDate(val year: Int, val month: Int, val day: Int)

fun SimpleDate.format(): String {
return "%04d-%02d-%02d".format(year, month, day)
}

fun SimpleDate.isWeekend(): Boolean {
// Calcul simple du jour de la semaine (Zeller's congruence)
val y = if (month < 3) year - 1 else year
val m = if (month < 3) month + 12 else month
val dayOfWeek = (day + (13 * (m + 1) / 5) + (y % 100) +
(y % 100) / 4 + (y / 100) / 4 - 2 * (y / 100)) % 7
return dayOfWeek == 0 || dayOfWeek == 6 // Sam/Dim
}

fun main() {
val date = SimpleDate(2024, 12, 25)
println(date.format()) // 2024-12-25
}

🔍 Extensions nullable

Extension sécurisée contre null

// null ou chaîne vide
fun String?.isNullOrEmpty(): Boolean {
return this == null || this.isEmpty()
}

// Retourner une valeur par défaut
fun String?.orDefault(default: String): String {
return this ?: default
}

fun main() {
val text: String? = null

println(text.isNullOrEmpty()) // true
println(text.orDefault("기본값")) // 기본값
}

🎨 Utilisation avancée

Extension générique

// Mélanger une collection
fun <T> List<T>.shuffled(): List<T> {
return this.shuffled()
}

// Transformation conditionnelle
fun <T, R> T.letIf(condition: Boolean, block: (T) -> R): R? {
return if (condition) block(this) else null
}

fun main() {
val numbers = listOf(1, 2, 3, 4, 5)
println(numbers.shuffled())

val result = "hello".letIf(true) { it.uppercase() }
println(result) // HELLO
}

Fonction infixe

// Notation infixe
infix fun Int.multipliedBy(other: Int): Int {
return this * other
}

infix fun String.concat(other: String): String {
return "$this $other"
}

fun main() {
println(5 multipliedBy 3) // 15

val greeting = "Hello" concat "World"
println(greeting) // Hello World
}

🛠️ Collection d'extensions pratiques

Extensions de validation

// Validation d'email
fun String.isValidEmail(): Boolean {
val pattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+"
return this.matches(pattern.toRegex())
}

// Force du mot de passe
fun String.isStrongPassword(): Boolean {
return this.length >= 8 &&
this.any { it.isDigit() } &&
this.any { it.isUpperCase() } &&
this.any { it.isLowerCase() }
}

// Validation d'URL
fun String.isValidUrl(): Boolean {
return this.startsWith("http://") || this.startsWith("https://")
}

fun main() {
println("hong@example.com".isValidEmail()) // true
println("Password123".isStrongPassword()) // true
println("https://kotlin.org".isValidUrl()) // true
}

Extensions de conversion

// CamelCase → snake_case
fun String.toSnakeCase(): String {
return this.replace(Regex("([a-z])([A-Z])")) {
"${it.groupValues[1]}_${it.groupValues[2]}"
}.lowercase()
}

// snake_case → CamelCase
fun String.toCamelCase(): String {
return this.split("_").mapIndexed { index, word ->
if (index == 0) word else word.capitalize()
}.joinToString("")
}

fun main() {
println("userName".toSnakeCase()) // user_name
println("user_name".toCamelCase()) // userName
}

🤔 Questions fréquentes

Q1. Où définir les fonctions d'extension ?

R : Généralement dans un fichier séparé !

// StringExtensions.kt
fun String.isEmail(): Boolean {
return this.contains("@")
}

// NumberExtensions.kt
fun Int.isEven(): Boolean {
return this % 2 == 0
}

// Pour utiliser, importez
import com.example.extensions.*

Q2. Que se passe-t-il si le nom est identique à une méthode existante ?

R : La méthode existante a la priorité !

class MyClass {
fun test() {
println("원본 메서드")
}
}

// Fonction d'extension (ne sera pas appelée !)
fun MyClass.test() {
println("확장 함수")
}

fun main() {
MyClass().test() // 원본 메서드
}

Q3. Peut-on accéder aux membres privés ?

R : Non !

class Person(private val age: Int)

// ❌ Accès privé impossible
fun Person.getAge(): Int {
// return this.age // Erreur !
return 0
}

🎬 Conclusion

Rendez votre code plus pratique avec les fonctions d'extension !

Résumé des points clés :
✅ Ajouter des fonctionnalités sans modifier la classe existante
✅ Syntaxe fun Type.nomFonction()
✅ Extension possible pour les types nullable
✅ Accès impossible aux membres privés
✅ Utilisation comme fonctions utilitaires

Prochaine étape : Apprenez à gérer les erreurs en toute sécurité dans Gestion des exceptions !