Custom getters and setters
📖 Scenario: You are creating a simple Kotlin class to represent a bank account. You want to control how the balance is accessed and changed by using custom getters and setters.
🎯 Goal: Build a Kotlin class BankAccount with a balance property. Use custom getter to show the balance with a message, and a custom setter to prevent setting a negative balance.
📋 What You'll Learn
Create a class called
BankAccount with a balance property of type Double initialized to 0.0Add a custom getter for
balance that returns the balance as a string with the message: "Current balance: $X" where X is the balanceAdd a custom setter for
balance that only updates the balance if the new value is not negativeCreate an instance of
BankAccount, set the balance to 100.0, then try to set it to -50.0, and finally print the balance💡 Why This Matters
🌍 Real World
Bank accounts and financial apps often need to control how money values are accessed and changed to avoid errors or fraud.
💼 Career
Understanding custom getters and setters is important for writing safe and clear Kotlin code in real-world applications.
Progress0 / 4 steps