Welcome to the Kotlin Getters and Setters tutorial! In this comprehensive guide, we'll explore these essential concepts, helping you write clean, efficient, and maintainable code in your projects.
Getters and Setters are special methods in Kotlin that allow you to access and modify the properties of a class, respectively. They follow a simple naming convention:
get keyword and are used to read the value of a property.set keyword and are used to write a new value to a property.Using getters and setters provides multiple benefits:
Let's create a simple Kotlin class with a property, and then add getters and setters to it.
class Person(var name: String, var age: Int) {
// Getter for the name property
val fullName: String
get() {
return "$name Surname"
}
// Setter for the age property with input validation
fun setAge(value: Int) {
if (value < 0) {
throw IllegalArgumentException("Age must be a positive number.")
}
this.age = value
}
}In the example above, we've created a Person class with two properties: name and age. We've added a fullName property that returns a full name using a getter. Additionally, we've added a setter for the age property with input validation to ensure the age is always a positive number.
To access the getters and setters, you can create instances of the Person class and manipulate them as follows:
fun main() {
val person = Person("John", 25)
println(person.fullName) // Output: John Surname
person.setAge(30)
println(person.age) // Output: 30
}What are the two main purposes of Getters and Setters in Kotlin?
That's it for the Kotlin Getters and Setters tutorial! By now, you should have a good understanding of how they work and when to use them. As you continue to learn Kotlin, you'll find getters and setters to be essential tools in your programming toolbox.
Happy coding! 💡🎯