using kotlin by keyword
The by keyword, however, is a native feature built directly into core Kotlin. It is called Property Delegation, and its main job is to let you hand over the responsibility of reading and writing a variable to a helper class.
Here is a simple, real-world example of how by can be used to automatically format a string (like capitalizing a user's name) every time you save a value to it.
import kotlin.reflect.KProperty
// 1. Create the Delegate class that handles the background work
class CapitalizeDelegate {
private var actualValue: String = ""
// Intercepts whenever someone reads the variable: "println(name)"
operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
return actualValue
}
// Intercepts whenever someone updates the variable: "name = 'alex'"
operator fun setValue(thisRef: Any?, property: KProperty<*>, newValue: String) {
// Automatically capitalize the first letter before storing it
actualValue = newValue.replaceFirstChar { it.uppercase() }
}
}
fun main() {
println("--- Kotlin 'by' Delegate Playground ---")
// 2. We use 'by' to attach our delegate class to this variable
var userName by CapitalizeDelegate()
// Assign a lowercase value
userName = "alexander"
// When we print it, look what happens!
println("The stored username is: $userName")
// Assign another lowercase value
userName = "sarah"
println("The stored username is: $userName")
}What problem does
bysolve?Imagine you have 10 different variables across your app that all need to be trimmed or capitalized before being saved to a database.
Without
by: You would have to manually write.replaceFirstChar { ... }or call a helper function every single time you assign a value to any of those variables. It's easy to forget one and cause a bug.With
by: You write the logic once inside the delegate class. Then, you can apply that behavior to any variable in your entire project by just typingby CapitalizeDelegate().
The Core Magic of by
The by keyword is essentially a syntax trick. When Kotlin compiles your code, it turns userName = "alexander" into a function call behind the scenes: delegate.setValue(..., "alexander").
It completely hides the background logic so your main code looks like standard, clean variables.
Comments