Classes & Data Classes
Properties, methods, data classes, and mutable state.
1. Classes and properties
A class has a primary constructor with val/var properties. Methods go inside the body:
class Point(val x: Int, val y: Int) {
fun describe(): String = "Point at ($x, $y)"
}
val p = Point(3, 4)
p.x // 3
p.describe() // "Point at (3, 4)"
val properties are read-only; var properties are mutable.
2. Add a method
Add a member function describe() to Point that returns "Point at (X, Y)" — for example, Point(3, 4).describe() returns "Point at (3, 4)". Use string templates.
Starter code
class Point(val x: Int, val y: Int) {
fun describe(): String {
return ""
}
}3. data classes and copy()
A data class automatically generates equals, hashCode, toString, and a copy method:
data class User(val name: String, val score: Int)
val u = User("Ada", 90)
println(u) // User(name=Ada, score=90)
val u2 = u.copy(score = 100) // new User; u is unchanged
copy is the idiomatic way to build a "modified" version of an immutable value — pass only the fields that change.
4. Use copy()
Use u.copy(score = u.score + by) inside bumpScore to return a new User with the score increased by by. The original must not be modified.
Starter code
data class User(val name: String, val score: Int)
fun bumpScore(u: User, by: Int): User {
return u
}5. Mutable state inside classes
For things that genuinely change over time, use a var property and a method that updates it:
class Counter {
var count: Int = 0
fun bump() { count++ }
}
val c = Counter()
c.bump(); c.bump()
c.count // 2
Reach for this when the object models real state (a counter, a connection pool, a session). Otherwise prefer val + copy.
6. Counter
Implement the Counter class with:
- a
var countstarting at0 - a method
bump()that incrementscountby 1
Starter code
class Counter {
var count: Int = 0
fun bump() {
// increment count
}
}Run this Kotlin lesson in your browser
SnipDojo ships an in-browser Kotlin editor with the exercises above already wired to tests. Sign in with Google to edit the starter code, run it, and track your progress toward the free certificate — no installs and no local toolchain.
Sign in to run this code →