Design Converter
Education
Software Development Executive - III
Last updated on Oct 25, 2024
Last updated on Oct 25, 2024
Kotlin, a modern programming language, has gained immense popularity due to its concise syntax and powerful features. Among these features, Kotlin member variables play a crucial role in object-oriented programming.
This blog will provide a detailed overview of Kotlin member variables, including the usage of keywords like var and val, the concept of primary constructors, and how to effectively create classes.
Let's get started!
In Kotlin, a class is a blueprint for creating objects. It can contain member variables, which define the state of an object, as well as functions that represent its behavior. Kotlin member variables can be mutable or immutable, determined by whether you use the var or val keyword.
• Mutable Properties: Defined using the var keyword, these variables can change their values after initialization.
• Immutable Properties: Defined using the val keyword, these variables are read-only and cannot be reassigned once initialized.
This distinction is essential in Kotlin as it promotes safer code practices and helps prevent unintended changes to variable values.
To better understand how to create classes and define member variables, let’s consider a simple Person class:
1class Person(val firstname: String, val lastname: String, var age: Int) { 2 init { 3 println("Created Person: $firstname $lastname, Age: $age") 4 } 5 6 fun displayInfo() { 7 println("Name: $firstname $lastname, Age: $age") 8 } 9} 10 11fun main() { 12 val person = Person("John", "Doe", 30) 13 person.displayInfo() 14}
In the example above, the Person class uses the primary constructor to define its properties. The firstname and lastname are defined with the val keyword, making them immutable. The age property, on the other hand, is defined with the var keyword, allowing it to be modified later.
The primary constructor in Kotlin provides a concise way to initialize properties when you create an instance of a class. It appears directly after the class name and can include parameters that correspond to the properties of the class.
In our previous example, the primary constructor is used to initialize the firstname, lastname, and age properties:
1class Person(val firstname: String, val lastname: String, var age: Int)
This line defines three member variables of the class Person, utilizing the val and var keywords appropriately. When you create a new instance of the Person class, you provide values for these parameters, which are then assigned to the respective properties.
Kotlin allows you to define initializer blocks that can contain code that runs during object instantiation. You can use init blocks to set up additional properties or execute logic after the primary constructor completes.
In the earlier Person example, the init block is utilized to print a message when a Person object is created:
1init { 2 println("Created Person: $firstname $lastname, Age: $age") 3}
This block runs immediately after the primary constructor and is useful for executing any setup code.
Kotlin also supports the use of custom getters and setters. These allow you to define how properties are accessed and modified. For instance, you can create a property that has a backing field and customize how the value is read or written.
Here’s an example that demonstrates a custom setter for the age property:
1class Person(val firstname: String, val lastname: String) { 2 var age: Int = 0 3 private set(value) { 4 if (value >= 0) { 5 field = value // backing field 6 } else { 7 println("Age cannot be negative!") 8 } 9 } 10} 11 12fun main() { 13 val person = Person("Jane", "Doe") 14 person.age = 25 // Valid assignment 15 println("${person.firstname} ${person.lastname} is ${person.age} years old.") 16 17 person.age = -5 // Invalid assignment 18}
In this example, the age property has a custom setter that includes a validation check. If an attempt is made to set a negative age, a warning message is printed, and the value is not changed.
Kotlin allows you to define visibility modifiers for class properties, which control the access level of those properties. The primary modifiers are public, private, protected, and internal.
Using the private modifier ensures that the property cannot be accessed outside the class:
1class Person(val firstname: String, private val lastname: String) { 2 fun getFullName(): String { 3 return "$firstname $lastname" 4 } 5}
In this case, the lastname property is private, meaning it can only be accessed within the Person class, promoting encapsulation.
In summary, Kotlin member variables are a fundamental aspect of the language, allowing you to define the state of objects within classes. By using the var and val keywords, you can create mutable and immutable properties that enhance code safety. The primary constructor and init blocks facilitate the creation and initialization of these properties, while custom getters and setters allow for enhanced control over property access.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.