0
0
Kotlinprogramming~30 mins

Custom getters and setters in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
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.0
Add a custom getter for balance that returns the balance as a string with the message: "Current balance: $X" where X is the balance
Add a custom setter for balance that only updates the balance if the new value is not negative
Create 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
1
Create the BankAccount class with a private balance
Create a Kotlin class called BankAccount with a balance property of type Double initialized to 0.0.
Kotlin
Need a hint?

Use var balance: Double = 0.0 inside the class.

2
Add a custom getter for balance
Add a custom getter for the balance property that returns a String with the message: "Current balance: $X" where X is the current balance value.
Kotlin
Need a hint?

Create a new val displayBalance with a custom getter that returns the message string.

3
Add a custom setter to prevent negative balance
Add a custom setter for the balance property that only updates the balance if the new value is not negative. If the new value is negative, do not change the balance.
Kotlin
Need a hint?

Use set(value) { if (value >= 0) field = value } to protect the balance.

4
Create an instance, set balances, and print
Create an instance of BankAccount called account. Set the balance to 100.0, then try to set it to -50.0. Finally, print account.displayBalance.
Kotlin
Need a hint?

Remember to create account, set balance twice, and print account.displayBalance.