Classes, Data Classes and Objects
Harry
· 23 Sep 2026
· 3 views
Log in to track your progress and mark lessons complete.
Sponsored
Primary Constructors
class Book(val title: String, var price: Int) {
init { require(price >= 0) { "price must be positive" } }
}Data Classes
data class User(val name: String, val email: String)
val u1 = User("Ravi", "ravi@test.com")
val u2 = u1.copy(email = "r@test.com") // changed copy
println(u1) // auto toString, equals, hashCodeobject: Singletons and Companions
object Config { const val BASE_URL = "https://groovygrails.in" }
class Order {
companion object {
fun guestCheckout() = Order()
}
}Use object for singletons and companion object for factory methods and constants - the clean static replacement.
Properties, Getters, Lateinit
- Custom accessors:
val slug get() = title.slug(). lateinit varfor injected fields set after construction.by lazyfor expensive values computed once on first use.
- Constructors are concise; init blocks validate.
- data class ends POJO boilerplate forever.
- object plus companion replace statics cleanly.