🔧 Funciones de extensión
📖 ¿Qué son las funciones de extensión?
Las funciones de extensión (Extension Functions) son una característica que permite agregar nuevas funciones a clases existentes sin modificarlas. ¡Puede usarlas como si fueran métodos originales!
💡 Uso básico
Primera función de extensión
// ¡Agregar nueva función a 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
}
Propiedades de extensión
val String.firstChar: Char
get() = if (this.isNotEmpty()) this[0] else ' '
fun main() {
println("Hello".firstChar) // H
println("Kotlin".firstChar) // K
}
🎯 Ejemplos prácticos
Utilidades de cadenas
// Formato de número telefónico
fun String.toPhoneFormat(): String {
return if (this.length == 11) {
"${substring(0, 3)}-${substring(3, 7)}-${substring(7)}"
} else {
this
}
}
// Truncar cadena
fun String.truncate(length: Int): String {
return if (this.length > length) {
"${substring(0, length)}..."
} else {
this
}
}
// Extraer solo números
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
}
Utilidades numéricas
// Determinar si es par
fun Int.isEven(): Boolean = this % 2 == 0
// Verificar rango
fun Int.isBetween(min: Int, max: Int): Boolean {
return this in min..max
}
// Formato de moneda
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원
}
Utilidades de colecciones
// Segundo elemento seguro
fun <T> List<T>.secondOrNull(): T? {
return if (this.size >= 2) this[1] else null
}
// Primer índice que cumple condición
fun <T> List<T>.indexOfFirstOrNull(predicate: (T) -> Boolean): Int? {
val index = this.indexOfFirst(predicate)
return if (index >= 0) index else null
}
// Agrupar lista en grupos de n
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 (índice)
println(numbers.chunked(2)) // [[1, 2], [3, 4], [5]]
}
Fecha/Hora (versión 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 {
// Cálculo simple de día de la semana (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 // Sáb/Dom
}
fun main() {
val date = SimpleDate(2024, 12, 25)
println(date.format()) // 2024-12-25
}
🔍 Extensiones nullable
Extensiones seguras para null
// Null o cadena vacía
fun String?.isNullOrEmpty(): Boolean {
return this == null || this.isEmpty()
}
// Retornar valor predeterminado
fun String?.orDefault(default: String): String {
return this ?: default
}
fun main() {
val text: String? = null
println(text.isNullOrEmpty()) // true
println(text.orDefault("valor predeterminado")) // valor predeterminado
}
🎨 Uso avanzado
Extensiones genéricas
// Mezclar colección
fun <T> List<T>.shuffled(): List<T> {
return this.shuffled()
}
// Transformación condicional
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
}
Funciones infix
// Notación infix
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
}
🛠️ Colección de extensiones prácticas
Extensiones de validación
// Validación de email
fun String.isValidEmail(): Boolean {
val pattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+"
return this.matches(pattern.toRegex())
}
// Fortaleza de contraseña
fun String.isStrongPassword(): Boolean {
return this.length >= 8 &&
this.any { it.isDigit() } &&
this.any { it.isUpperCase() } &&
this.any { it.isLowerCase() }
}
// Validación de 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
}
Extensiones de conversión
// 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
}
🤔 Preguntas frecuentes
P1. ¿Dónde se definen las funciones de extensión?
R: ¡Generalmente en archivos separados!
// StringExtensions.kt
fun String.isEmail(): Boolean {
return this.contains("@")
}
// NumberExtensions.kt
fun Int.isEven(): Boolean {
return this % 2 == 0
}
// Para usar, importar
import com.example.extensions.*
P2. ¿Qué pasa si tiene el mismo nombre que un método existente?
R: ¡El método existente tiene prioridad!
class MyClass {
fun test() {
println("Método original")
}
}
// Función de extensión (¡no se llamará!)
fun MyClass.test() {
println("Función de extensión")
}
fun main() {
MyClass().test() // Método original
}
P3. ¿Se puede acceder a miembros privados?
R: ¡No!
class Person(private val age: Int)
// ❌ No se puede acceder a private
fun Person.getAge(): Int {
// return this.age // ¡Error!
return 0
}
🎬 Conclusión
¡Haga su código más conveniente con funciones de extensión!
Resumen clave:
✅ Agregar funcionalidades sin modificar clases existentes
✅ Forma: fun Tipo.nombreFuncion()
✅ También se pueden extender tipos nullable
✅ No se puede acceder a miembros private
✅ Usar como funciones de utilidad
Siguiente paso: ¡Aprenda a manejar errores de forma segura en Manejo de excepciones!