π§ Extension Functions
π What are Extension Functions?β
Extension Functions are a feature that allows you to add new functions to existing classes without modifying them. You can use them just like original methods!
π‘ Basic Usageβ
Your First Extension Functionβ
// Add a new function to 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
}
Extension Propertiesβ
val String.firstChar: Char
get() = if (this.isNotEmpty()) this[0] else ' '
fun main() {
println("Hello".firstChar) // H
println("Kotlin".firstChar) // K
}
π― Practical Examplesβ
String Utilitiesβ
// Phone number format
fun String.toPhoneFormat(): String {
return if (this.length == 11) {
"${substring(0, 3)}-${substring(3, 7)}-${substring(7)}"
} else {
this
}
}
// String truncation
fun String.truncate(length: Int): String {
return if (this.length > length) {
"${substring(0, length)}..."
} else {
this
}
}
// Extract numbers only
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("Price: 1,500won".numbersOnly()) // 1500
}
Number Utilitiesβ
// Check if even
fun Int.isEven(): Boolean = this % 2 == 0
// Range check
fun Int.isBetween(min: Int, max: Int): Boolean {
return this in min..max
}
// Currency format
fun Int.toCurrency(): String {
return "%,d won".format(this)
}
fun main() {
println(4.isEven()) // true
println(7.isEven()) // false
println(50.isBetween(0, 100)) // true
println(1500000.toCurrency()) // 1,500,000 won
}
Collection Utilitiesβ
// Safe second element
fun <T> List<T>.secondOrNull(): T? {
return if (this.size >= 2) this[1] else null
}
// First index that matches condition
fun <T> List<T>.indexOfFirstOrNull(predicate: (T) -> Boolean): Int? {
val index = this.indexOfFirst(predicate)
return if (index >= 0) index else null
}
// Chunk list into groups of 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 (index)
println(numbers.chunked(2)) // [[1, 2], [3, 4], [5]]
}
Date/Time (Simple Version)β
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 {
// Simple day of week calculation (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 // Sat/Sun
}
fun main() {
val date = SimpleDate(2024, 12, 25)
println(date.format()) // 2024-12-25
}
π Nullable Extensionsβ
Null-Safe Extensionsβ
// Null or empty string
fun String?.isNullOrEmpty(): Boolean {
return this == null || this.isEmpty()
}
// Return default value
fun String?.orDefault(default: String): String {
return this ?: default
}
fun main() {
val text: String? = null
println(text.isNullOrEmpty()) // true
println(text.orDefault("default value")) // default value
}
π¨ Advanced Usageβ
Generic Extensionsβ
// Shuffle collection
fun <T> List<T>.shuffled(): List<T> {
return this.shuffled()
}
// Conditional transformation
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
}
Infix Functionsβ
// Infix notation
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
}
π οΈ Practical Extension Collectionβ
Validation Extensionsβ
// Email validation
fun String.isValidEmail(): Boolean {
val pattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+"
return this.matches(pattern.toRegex())
}
// Password strength
fun String.isStrongPassword(): Boolean {
return this.length >= 8 &&
this.any { it.isDigit() } &&
this.any { it.isUpperCase() } &&
this.any { it.isLowerCase() }
}
// URL validation
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
}
Conversion Extensionsβ
// 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
}
π€ Frequently Asked Questionsβ
Q1. Where should I define extension functions?β
A: Usually in separate files!
// StringExtensions.kt
fun String.isEmail(): Boolean {
return this.contains("@")
}
// NumberExtensions.kt
fun Int.isEven(): Boolean {
return this % 2 == 0
}
// Import when using
import com.example.extensions.*
Q2. What if there's a method with the same name?β
A: The existing method takes priority!
class MyClass {
fun test() {
println("Original method")
}
}
// Extension function (won't be called!)
fun MyClass.test() {
println("Extension function")
}
fun main() {
MyClass().test() // Original method
}
Q3. Can I access private members?β
A: No, you cannot!
class Person(private val age: Int)
// β Cannot access private
fun Person.getAge(): Int {
// return this.age // Error!
return 0
}
π¬ Conclusionβ
Make your code more convenient with extension functions!
Key Takeaways:
β
Add functionality without modifying existing classes
β
Use fun Type.functionName() format
β
Can extend nullable types
β
Cannot access private members
β
Great for utility functions
Next Step: Learn how to safely handle errors in Exception Handling!