Kotlin Getters and Setters Tutorial 🎯

beginner
21 min

Kotlin Getters and Setters Tutorial 🎯

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.

What are Getters and Setters? 📝

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:

  • Getters use the get keyword and are used to read the value of a property.
  • Setters use the set keyword and are used to write a new value to a property.

Why Use Getters and Setters? 💡

Using getters and setters provides multiple benefits:

  • Data Encapsulation: By controlling the access to the properties, we can hide the internal details of a class and provide a clean, user-friendly interface.
  • Input Validation: Setters can be used to validate the incoming data before assigning it to the property.
  • Immutable Objects: You can create immutable objects by not providing a setter for a property.

Creating Getters and Setters 📝

Let's create a simple Kotlin class with a property, and then add getters and setters to it.

kotlin
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.

Accessing Getters and Setters 📝

To access the getters and setters, you can create instances of the Person class and manipulate them as follows:

kotlin
fun main() { val person = Person("John", 25) println(person.fullName) // Output: John Surname person.setAge(30) println(person.age) // Output: 30 }

Quiz 🎯

Quick Quiz
Question 1 of 1

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! 💡🎯