Kotlin data classes are a powerful feature that allows developers to create classes specifically for holding data. These classes automatically generate useful methods like equals()
, hashCode()
, and toString()
, which makes them ideal for representing simple data structures. In this article, we will explore three diverse examples of Kotlin data classes that illustrate their practical use cases.
In a typical application, you might need to manage user profiles. A data class can efficiently hold user information such as name, email, and age.
data class UserProfile(
val name: String,
val email: String,
val age: Int
)
fun main() {
val user = UserProfile(name = "Jane Doe", email = "jane.doe@example.com", age = 30)
println(user)
}
UserProfile
objects to manage multiple users in your application.In e-commerce applications, products often have various attributes. A data class can represent a product, including its ID, name, price, and stock status.
data class Product(
val id: Int,
val name: String,
val price: Double,
var inStock: Boolean
)
fun main() {
val product = Product(id = 101, name = "Wireless Mouse", price = 29.99, inStock = true)
println(product)
}
inStock
is mutable, allowing you to update the stock status as needed.For library management systems, a data class can help manage information about books, including title, author, and ISBN.
data class Book(
val title: String,
val author: String,
val isbn: String,
val publishedYear: Int
)
fun main() {
val book = Book(title = "1984", author = "George Orwell", isbn = "978-0451524935", publishedYear = 1949)
println(book)
}
publishedYear
property could be useful for filtering books by publication date.These examples of Kotlin data classes demonstrate their versatility and ease of use in different programming scenarios. Leveraging data classes can significantly enhance code readability and maintainability.