Kotlin
Beginner
1 min read
Classes, Constructors and Properties
Example
// Primary constructor with properties
class Person(val name: String, var age: Int) {
// Property with custom getter
val isAdult: Boolean
get() = age >= 18
// Property with backing field and custom setter
var email: String = ""
set(value) {
require(value.contains('@')) { "Invalid email: $value" }
field = value // 'field' refers to the backing field
}
// Init block — runs during construction
init {
require(name.isNotBlank()) { "Name must not be blank" }
require(age >= 0) { "Age must be non-negative" }
}
// Secondary constructor
constructor(name: String) : this(name, 0)
override fun toString() = "Person(name=$name, age=$age)"
}
// Sealed class hierarchy
sealed class Shape {
abstract fun area(): Double
class Circle(val radius: Double) : Shape() { override fun area() = Math.PI * radius * radius }
class Rectangle(val w: Double, val h: Double): Shape() { override fun area() = w * h }
}
fun main() {
val alice = Person("Alice", 28)
alice.email = "alice@example.com"
println(alice)
println("Adult: ${alice.isAdult}")
val shapes: List<Shape> = listOf(Shape.Circle(5.0), Shape.Rectangle(3.0, 4.0))
shapes.forEach { s ->
val desc = when (s) {
is Shape.Circle -> "Circle area=${s.area()}"
is Shape.Rectangle -> "Rect area=${s.area()}"
}
println(desc)
}
}
Related Resources
Kotlin Reference
Complete tag & property list
Kotlin How-To Guides
Step-by-step practical guides
Kotlin Exercises
Practice what you've learned
More in Kotlin