Explain it simply
Explain it simply
A class is a blueprint, and an object is one thing built from it. A house plan says every house has a door and some rooms, yet each real house has its own paint colour and its own family inside. In code, the Customer class says every customer has a name and can print it, and each Customer object holds its own name.
Kotlin keeps the vocabulary small. You write the class once, then call it like a function, Customer(), to build an object; there is no new keyword. The variables inside the class are properties, the functions inside it are members, and you reach both with a dot, as in customer.name.
Problem → Why → Solution
The problem: loose variables cannot protect themselves
Imagine a small banking script with no classes. The balance is a top-level variable, and any function in the file is free to change it. One careless line stores a negative number, nothing complains, and three weeks later a bug report arrives saying the account shows -9999.
The data and the rules about the data live in different places. Nothing says that a balance should grow only through deposits, and with two accounts you would need two variables plus two copies of every function. What you want is the data packaged together with the only code allowed to touch it.
var balance = 100
fun withdraw(amount: Int) {
balance -= amount
}
fun main() {
withdraw(250) // allowed: balance is now -150
balance = -9999 // also allowed: any code may write anything
println(balance)
}Why is a loose variable dangerous?
A top-level variable has no owner, so no code can promise anything about it. A class gives data an owner: its members can protect rules (a property whose setter is private cannot be written from outside), and each object carries its own copy of the data. That is encapsulation: callers see a small public surface, and the rules live in one place where you can test them.
Core concept: a property is a field plus accessors
A class bundles properties (data) and member functions (behaviour). Writing var name = "" inside the class declares a property, and Kotlin treats it as more than a field. For every property the compiler creates a hidden backing field plus a getter, and for a var also a setter. When you write customer.name you are calling the getter, and customer.name = "Kyaw" calls the setter. That is why you can change how a property works later without touching the code that uses it.
Kotlin lets you write those accessors yourself. A custom setter receives the new value as value and stores it in the backing field through the identifier field; writing name = value inside the setter would call the setter again and loop forever. A property with only a getter, such as val isOverdrawn: Boolean get() = balance < 0, has no backing field at all: it is computed each time it is read. Add private set after a var and everybody can read the property, but only code inside the class can change it.
Two rules explain most beginner errors. First, a property must be initialised: var name: String on its own fails with "property must be initialized or be abstract", so give it a value or set it from a constructor, which the next lesson covers. Second, classes are public and final by default, and members are public by default, so mark helpers private instead of hoping nobody calls them.
Finally, an object is a reference. val other = customer does not copy the customer; both names point at the same object, so a change through one is visible through the other, and customer === other is true. Two separate calls to Customer() give two objects with their own state. When you need exactly one instance of something, Kotlin has the object declaration, and members that belong to the class itself rather than to each instance go inside a companion object. Both are shown below.
| Declaration | Who can read | Who can write |
|---|---|---|
| var x = 0 | Everywhere | Everywhere |
| val x = 0 | Everywhere | Nobody after construction |
| var x = 0 + private set | Everywhere | Inside the class only |
| val x: T get() = ... | Everywhere (computed) | Nobody |
- The class describes the blueprint
- Customer() builds one object
- Each object keeps its own state
- Dot access calls getters and setters
Two objects of one class never share state unless you share a reference, and a private setter limits who may change it.
General pattern
class ClassName {
var property: Type = initialValue
val readOnly: Type = initialValue
fun member(param: Type): Result {
// use property here
}
}
val obj = ClassName() // no new keyword
obj.property = newValue // calls the setter
obj.member(argument)Inside the class body, properties are declared with var or val and member functions with fun. To create an object, call the class name like a function. After that, a dot reads or writes properties and calls members.
Example: a Customer that stores a name and prints it
This is the smallest useful class. Customer holds one property and one member function, and main creates an object, sets the property, then asks the object to print itself. Notice that printName() reads name without writing customer. in front: inside a member function, the object's own properties are directly in scope.
class Customer {
var name = ""
fun printName() {
println("Customer name is $name")
}
}
fun main() {
val customer = Customer()
customer.name = "Kyaw"
customer.printName()
}Code breakdown
- The blueprint
class Customer {The class keyword starts a new blueprint. With no modifier it is public and final, so no other class can inherit from it.
- A property
var name = ""This declares a property. The type String is inferred from the "" initialiser. Because it is a var, Kotlin generates both a getter and a setter, and the initial value keeps the declaration valid.
- A member function
fun printName() {A function inside a class is a member. It sees the properties of the object it was called on implicitly, so you do not need to write this.
- Read the property
println("Customer name is $name")The string template reads name through its getter. Each object has its own name, so every customer prints its own.
- Create an object
val customer = Customer()Calling the class name like a function builds a new object; there is no new. val means the variable cannot point at a different object, while the object's var properties can still change.
- Write the property
customer.name = "Kyaw"This assignment calls the setter. The default setter simply stores the value in the backing field, and printName() then sees "Kyaw".
Customer name is Kyaw- customer.name = "Kyaw" runs
- Kotlin calls the setter of name
- What does the setter do with the value?
Default setter
stores the value in the backing field
Custom setter
may trim, validate or reject the value first, then stores it with field
Custom getters, setters and private set
Account below shows all three tools. balance can be read by anyone but written only inside the class. nickname trims its input and falls back to the owner's name when it is blank, storing through field. isOverdrawn has no storage and is recomputed on every read. The only way to change balance from outside is deposit(), which uses require() to reject nonsense. An assignment such as acc.balance = 5 in main is refused by the compiler with "cannot access 'balance'".
class Account(val owner: String) {
var balance: Int = 0
private set // readable everywhere, writable only here
var nickname: String = owner
set(value) {
field = value.trim().ifEmpty { owner } // field is the hidden backing field
}
val isOverdrawn: Boolean
get() = balance < 0 // computed on every read, nothing stored
fun deposit(amount: Int) {
require(amount > 0) { "amount must be positive" }
balance += amount
}
}
fun main() {
val acc = Account("Mya")
acc.deposit(50)
acc.nickname = " "
println(acc.nickname)
acc.nickname = " Mya M "
println(acc.nickname + "|")
println(acc.balance)
println(acc.isOverdrawn)
}object and companion object
An object declaration creates a class and its only instance in one step. AppSettings is already an object, so you never write AppSettings(), and its state lives for the whole program. Use it for things that are genuinely single, such as configuration or a registry. A companion object belongs to a class: Customer.create() and Customer.DEFAULT_NAME are called on the class name, not on an instance, and they replace Java's static members. const val is allowed for compile-time constants of primitive or String type. Global mutable state inside an object is shared by every part of the program, tests included, so keep it small.
object AppSettings {
var darkMode = false
fun toggle() {
darkMode = !darkMode
}
}
class Customer(val name: String) {
companion object {
const val DEFAULT_NAME = "guest"
private var created = 0
fun create(name: String = DEFAULT_NAME): Customer {
created += 1
return Customer(name)
}
fun createdCount(): Int = created
}
}
fun main() {
AppSettings.toggle()
println(AppSettings.darkMode)
val a = Customer.create("Kyaw")
val b = Customer.create()
println(a.name + " and " + b.name)
println(Customer.createdCount())
println(Customer.DEFAULT_NAME)
}In real projects
Where this shows up in real projects
In real projects, classes represent the meaningful entities such as User, Order, Product and Course, and what matters most is controlling how their state may change. An Order class, for example, can expose status for the UI to read while a private set lets only functions like markPaid() and ship() change it, so an order can never jump from NEW straight to DELIVERED. Those rules live in one class, so a single unit test can check them.
On Android every screen is a class and view models often keep their state behind a private set. On the server, service classes keep a repository or client as a property. Logger and configuration objects are common, but global objects are awkward to test, so important dependencies are better passed into a class. A companion object is the usual home for factory functions such as Customer.create() and for constants.
Common mistakes
Common mistakes
1. Leaving a property uninitialised
class C { var name: String } fails with "property must be initialized or be abstract". Give it a value, or fill it from a constructor. Reserve lateinit var for properties that a framework fills in later, because reading one too early throws "lateinit property title has not been initialized".
2. Assigning inside a setter without field
set(value) { name = value } compiles, but name = value calls the same setter again and the program dies with StackOverflowError when it runs. Write field = value to store straight into the backing field.
3. Thinking val makes the object immutable
val customer = Customer() protects the variable, not the object. If name is a var, customer.name = "x" still works, and val other = customer copies the reference, so both names change the same object. Declare properties that should never change as val.
Best practices
Best practices
- Start properties as val and make one a var only when it truly has to change.
- Put the rules for changing state into a function such as deposit() and keep the setter private.
- Keep object declarations for things that are genuinely single, and pass dependencies into classes instead of reaching into global objects.
Mini challenge
Mini challenge: a StepCounter class
Write a class that counts steps. Everyone may read the step count but only the class may change it, and the goal must never become an invalid value.
- steps starts at 0, can be read anywhere, but is changed only from inside the class (private set)
- goal is a var that defaults to 10000 and never becomes less than 1 (custom setter with field)
- walk(count) adds to steps and ignores zero or negative counts
- percent and reachedGoal are computed properties with getters (percent is capped at 100)
class StepCounter(val owner: String) {
// TODO: var steps, readable everywhere but writable only inside the class
// TODO: var goal = 10000 whose setter keeps it at 1 or more (use field)
// TODO: val percent (never above 100) and val reachedGoal, both as getters
// TODO: fun walk(count: Int) that ignores counts of zero or less
}
fun main() {
val counter = StepCounter("Aye")
// TODO: set the goal to 2000, then walk 500, -300 and 700
// TODO: print "Aye: 1200 steps, 60%" and then reachedGoal
// TODO: set goal to 0, print goal, walk 5000, print reachedGoal
}Expected: The program prints these four lines: Aye: 1200 steps, 60% false 1 true
Show hint
Put private set on the line after var steps: Int = 0. In the setter of goal use field = value.coerceAtLeast(1). Compute percent as minOf(100, steps * 100 / goal) inside a get().
Show solution
class StepCounter(val owner: String) {
var steps: Int = 0
private set
var goal: Int = 10000
set(value) {
field = value.coerceAtLeast(1)
}
val percent: Int
get() = minOf(100, steps * 100 / goal)
val reachedGoal: Boolean
get() = steps >= goal
fun walk(count: Int) {
if (count > 0) steps += count
}
}
fun main() {
val counter = StepCounter("Aye")
counter.goal = 2000
counter.walk(500)
counter.walk(-300)
counter.walk(700)
println("${counter.owner}: ${counter.steps} steps, ${counter.percent}%")
println(counter.reachedGoal)
counter.goal = 0
println(counter.goal)
counter.walk(5000)
println(counter.reachedGoal)
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A class is a blueprint; Customer() builds an object with no new keyword, and each object keeps its own state.
- A property is a backing field plus a getter (and a setter for var); customer.name = x calls the setter.
- A custom setter stores through field, a getter-only property is computed with no storage, and private set confines writes to the class.
- object declares a single instance, and companion object holds members that belong to the class itself.
Kotlin language guide — Kotlin