Welcome to our comprehensive guide on Kotlin Member Properties! In this tutorial, we'll dive deep into one of Kotlin's powerful features that simplifies object-oriented programming.
By the end of this lesson, you'll be able to:
In Kotlin, member properties are variables that are associated with a class or object. They help store and manage data within your objects, making your code cleaner and easier to read.
Let's start by declaring a simple property:
class Person {
var name: String = "John Doe"
}In the example above, name is a property of type String with an initial value of "John Doe". We've also declared it as var, meaning it's mutable and can be changed throughout the program.
Every property in Kotlin implicitly has two accessors: a getter and a setter.
The getter is a method that retrieves the value of a property. In most cases, Kotlin generates a getter method automatically when you declare a property.
class Person {
var name: String = "John Doe"
// Accessing the property
fun displayName() {
println(name)
}
}
fun main() {
val person = Person()
person.displayName() // Output: John Doe
}The setter is a method that sets the value of a property. If you don't provide an initial value for a property or if it's marked as constant, Kotlin will generate a setter method for you.
class Person {
var name: String = ""
set(value) {
field = value.capitalize() // Capitalize the first letter of the name
}
}
fun main() {
val person = Person()
person.name = "john doe"
println(person.name) // Output: John Doe
}Kotlin offers three types of properties:
var: Mutable properties that can be changed throughout the program.val: Immutable properties whose values cannot be changed once assigned.const: Constant properties that are evaluated at compile time and must be initialized with a constant expression.Companion properties are static properties that belong to the class itself, rather than an instance of the class. They are accessed using the ::class reference or the class name.
class Person {
companion object {
val MAX_AGE = 100
}
}
fun main() {
println(Person.MAX_AGE) // Output: 100
}Now that you understand the basics of member properties in Kotlin, let's put everything into practice.
class Employee(
var name: String,
var age: Int,
var salary: Double = 0.0
) {
companion object {
const val TAX_RATE = 0.15
}
fun calculateNetSalary() {
val netSalary = salary - (salary * TAX_RATE)
println("Net salary: $netSalary")
}
}
fun main() {
val employee = Employee("John Doe", 30, 5000.0)
employee.calculateNetSalary() // Output: Net salary: 4000.0
}What are member properties in Kotlin?
Congratulations on completing this tutorial on Kotlin Member Properties! You're one step closer to becoming a proficient Kotlin developer. Keep exploring the world of Kotlin and happy coding! 🎯