Bird
Raised Fist0
Kotlinprogramming~10 mins

Custom delegated properties in Kotlin - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Custom delegated properties
Define delegate class with getValue and setValue
↓
Create property using 'by' keyword with delegate instance
↓
Access property
→Delegate's getValue called
↓
Assign property
→Delegate's setValue called
↓
Property value updated
Custom delegated properties use a delegate class to control getting and setting a property via getValue and setValue methods.
Execution Sample
Kotlin
class Delegate {
  operator fun getValue(thisRef: Any?, property: kotlin.reflect.KProperty<*>): String {
    return "Hello"
  }
  operator fun setValue(thisRef: Any?, property: kotlin.reflect.KProperty<*>, value: String) {
    println("Setting value to $value")
  }
}

class Example {
  var prop: String by Delegate()
}

fun main() {
  val e = Example()
  println(e.prop)
  e.prop = "World"
}
This code shows a property 'prop' delegated to a custom Delegate class that prints on set and returns "Hello" on get.
Execution Table
StepActionMethod CalledInput ValueOutput/Effect
1Create Example instanceN/AN/AExample object created with prop delegated
2Access e.propgetValuethisRef=Example instance, property=propReturns "Hello"
3Print e.propN/A"Hello"Outputs: Hello
4Assign e.prop = "World"setValuethisRef=Example instance, property=prop, value="World"Prints: Setting value to World
5End of mainN/AN/AProgram ends
💡 Program ends after property get and set operations complete
Variable Tracker
VariableStartAfter Step 2After Step 4Final
e.propN/A"Hello" (returned by getValue)"World" (set by setValue, no stored value)No stored value, delegate controls behavior
Key Moments - 3 Insights
Why does e.prop print "Hello" even though we never assigned a value before?
Because the delegate's getValue method always returns "Hello" regardless of any assignment, as shown in execution_table step 2.
Does the delegate store the assigned value "World"?
No, the delegate's setValue only prints the assigned value but does not store it, so getValue always returns "Hello" (see steps 4 and 2).
What is the role of 'by Delegate()' in the property declaration?
It tells Kotlin to use the Delegate class to handle getting and setting the property, as shown in concept_flow and execution_table steps.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what does getValue return when e.prop is accessed?
A"World"
Bnull
C"Hello"
DThrows error
💡 Hint
Check execution_table row 2 where getValue returns "Hello"
At which step does the delegate print the assigned value?
AStep 2
BStep 4
CStep 1
DStep 3
💡 Hint
Look at execution_table row 4 where setValue prints the assigned value
If the delegate stored the assigned value, what would change in variable_tracker after step 4?
Ae.prop would show "World" after step 4
Be.prop would still show "Hello" after step 4
Ce.prop would be null after step 4
De.prop would cause an error after step 4
💡 Hint
variable_tracker shows e.prop does not store value now; storing would update it after step 4
Concept Snapshot
Custom delegated properties use a delegate class with operator functions getValue and setValue.
Declare property with 'by Delegate()' to delegate its behavior.
getValue controls what happens when property is read.
setValue controls what happens when property is assigned.
Delegate can store or compute values as needed.
This allows flexible property behavior beyond simple storage.
Full Transcript
Custom delegated properties in Kotlin let you control how a property is read and written by using a delegate class. This class must have operator functions getValue and setValue. When you declare a property with 'by Delegate()', Kotlin calls these functions instead of directly accessing the property. In the example, getValue always returns "Hello" and setValue prints the assigned value but does not store it. The execution table shows step-by-step how the property is accessed and assigned, and the variable tracker shows that the property value is controlled by the delegate, not stored normally. Key moments clarify why the property prints "Hello" even after assignment and the role of the delegate. The visual quiz tests understanding of these steps. This technique allows you to customize property behavior easily.

Practice

(1/5)
1. What is the main purpose of using custom delegated properties in Kotlin?
easy
A. To define extension functions for a class
B. To create multiple constructors for a class
C. To control how a property's value is stored and retrieved
D. To override the default toString() method

Solution

  1. Step 1: Understand property delegation concept

    Delegated properties let you customize how a property's value is handled behind the scenes.
  2. Step 2: Identify the purpose of custom delegation

    Custom delegated properties specifically allow control over getting and setting property values.
  3. Final Answer:

    To control how a property's value is stored and retrieved -> Option C
  4. Quick Check:

    Custom delegation = control property access [OK]
Hint: Delegation controls property get/set behavior [OK]
Common Mistakes:
  • Confusing delegation with constructors
  • Thinking delegation defines functions
  • Mixing delegation with method overriding
2. Which of the following is the correct syntax to declare a custom delegated property in Kotlin?
easy
A. val prop = Delegate()
B. val prop by Delegate()
C. val prop: Delegate by this
D. val prop delegate Delegate()

Solution

  1. Step 1: Recall Kotlin delegation syntax

    Delegated properties use the by keyword followed by a delegate instance.
  2. Step 2: Match correct syntax

    val prop by Delegate() correctly declares a delegated property.
  3. Final Answer:

    val prop by Delegate() -> Option B
  4. Quick Check:

    Delegation uses 'by' keyword [OK]
Hint: Look for 'by' keyword with delegate instance [OK]
Common Mistakes:
  • Using '=' instead of 'by' for delegation
  • Incorrect delegate type declaration
  • Missing parentheses for delegate constructor
3. What will be the output of the following Kotlin code?
class Delegate {
    operator fun getValue(thisRef: Any?, property: kotlin.reflect.KProperty<*>): String {
        return "Hello from delegate"
    }
}

class Example {
    val message: String by Delegate()
}

fun main() {
    val e = Example()
    println(e.message)
}
medium
A. Hello from delegate
B. null
C. Compilation error
D. Hello from Example

Solution

  1. Step 1: Understand getValue operator

    The getValue function returns the string "Hello from delegate" when the property is accessed.
  2. Step 2: Trace property access in main()

    Accessing e.message calls getValue and prints the returned string.
  3. Final Answer:

    Hello from delegate -> Option A
  4. Quick Check:

    Delegate getValue returns string [OK]
Hint: getValue defines returned property value [OK]
Common Mistakes:
  • Expecting default property value instead of delegate's
  • Confusing getValue with setValue
  • Assuming compilation error due to missing parameters
4. Identify the error in this Kotlin code using a custom delegated property:
class Delegate {
    operator fun getValue(thisRef: Any?, property: kotlin.reflect.KProperty<*>): Int {
        return 42
    }
}

class Example {
    var number: Int by Delegate()
}

fun main() {
    val e = Example()
    e.number = 10
    println(e.number)
}
medium
A. Delegate class must be an interface
B. Property number should be val, not var
C. getValue must return String, not Int
D. Delegate class lacks setValue operator function

Solution

  1. Step 1: Check property mutability and delegation

    The property number is var, so delegate must support both get and set.
  2. Step 2: Verify delegate methods

    The Delegate class only defines getValue, missing setValue needed for var.
  3. Final Answer:

    Delegate class lacks setValue operator function -> Option D
  4. Quick Check:

    var needs getValue and setValue [OK]
Hint: var properties need both getValue and setValue [OK]
Common Mistakes:
  • Forgetting setValue for var properties
  • Assuming getValue return type must be String
  • Thinking delegate must be interface
5. You want to create a custom delegated property that logs every time the property is read or written. Which of the following delegate implementations correctly achieves this?
class LoggingDelegate<T>(var value: T) {
    operator fun getValue(thisRef: Any?, property: kotlin.reflect.KProperty<*>): T {
        println("Getting value of ${property.name}")
        return value
    }

    operator fun setValue(thisRef: Any?, property: kotlin.reflect.KProperty<*>, newValue: T) {
        println("Setting value of ${property.name} to $newValue")
        value = newValue
    }
}

class Example {
    var data: String by LoggingDelegate("initial")
}

fun main() {
    val e = Example()
    e.data = "new"
    println(e.data)
}
hard
A. Logs on get and set, prints 'Setting value of data to new' then 'Getting value of data' and 'new'
B. Only logs on get, no output on set
C. Throws error because delegate class is not generic
D. Does not compile due to missing constructor parameters

Solution

  1. Step 1: Analyze delegate methods

    The delegate defines getValue and setValue with print statements logging property access.
  2. Step 2: Trace main function output

    Setting e.data = "new" prints setting log, then printing e.data triggers get log and prints value.
  3. Final Answer:

    Logs on get and set, prints 'Setting value of data to new' then 'Getting value of data' and 'new' -> Option A
  4. Quick Check:

    Delegate logs on get/set correctly [OK]
Hint: Check both getValue and setValue print logs [OK]
Common Mistakes:
  • Missing setValue causes no set logging
  • Assuming delegate must be non-generic
  • Forgetting to pass initial value to delegate
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard