Avatar ·

What does the `by` keyword do in Kotlin? Explain with examples

Hi everyone! I recently started learning Kotlin, switched from Java, and encountered syntax that is unclear to me. I see the `by` keyword in my colleagues' code, but I can't understand its purpose. \n\nFor example, I've seen code like this:\n\n```kotlin\nclass MyClass {\n var name: String by Delegates.observable("Initial") { prop, old, new ->\n println("$old -> $new")\n }\n}\n```\n\nOr this:\n\n```kotlin\nclass Derived(base: Base) : Base by base\n```\n\nI understand that it's somehow related to delegation, but it's not clear to me how it works under the hood. In Java, we just had inheritance and interfaces, but here it's some kind of magic. \n\nPlease explain what `by` is used for? In what cases should it be applied? And how does it work at the bytecode level? I'd appreciate simple examples to understand.