Classes, Data Classes and Objects

Harry · 23 Sep 2026 · 3 views
Log in to track your progress and mark lessons complete.

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, hashCode

object: 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 var for injected fields set after construction.
  • by lazy for expensive values computed once on first use.

Data class generates equals hashCode toString copy

Key Points

  • Constructors are concise; init blocks validate.
  • data class ends POJO boilerplate forever.
  • object plus companion replace statics cleanly.
Share this post:

Comments (0)

Please login or register to comment.

Create a free account to keep reading

You've enjoyed a free tutorial! Register (it's free) to unlock every tutorial, track your progress and save code.

or sign in with your account

Already have an account? Log in