Kotlin Classes โ Creating and Using Classes
A class is a blueprint for objects. Kotlin classes are concise โ properties and constructors can be declared in one line.
What You Will Learn
- Declare a class with a primary constructor
- Define properties and methods
- Create instances
- Use init blocks
- Understand val vs var in a class
Basic Class Declaration
Basic Class
class Person(val name: String, var age: Int) {
fun introduce() {
println("Hi, I am $name and I am $age years old.")
}
}
fun main() {
val person = Person("Juned", 25)
person.introduce()
person.age = 26 // mutable property
println(person.age)
}Person has two properties in the primary constructor. val name cannot be changed. var age can be reassigned. Methods are declared inside the class body.
init Block
init Block
class Circle(val radius: Double) {
val area: Double
init {
require(radius > 0) { "Radius must be positive" }
area = Math.PI * radius * radius
}
fun describe() = "Circle(r=$radius, area=${"%.2f".format(area)})"
}
fun main() {
val c = Circle(5.0)
println(c.describe())
}init runs when Circle is created. area is computed inside init. require validates the input and throws if false.
Secondary Constructor
Secondary Constructor
class Book(val title: String, val author: String) {
var pages: Int = 0
constructor(title: String, author: String, pages: Int) : this(title, author) {
this.pages = pages
}
override fun toString() = ""$title" by $author ($pages pages)"
}
fun main() {
val b1 = Book("Kotlin Guide", "KG Team")
val b2 = Book("Effective Kotlin", "M. Moskala", 350)
println(b1)
println(b2)
}The secondary constructor delegates to the primary with : this(). It sets the pages property afterward.
Practice Exercise
What prints? class Dog(val name: String) { fun bark() = println("$name says: Woof!") } fun main() { val d = Dog("Rex") d.bark() }
Quick Quiz
In Kotlin, how do you declare a class property in the primary constructor?
Frequently Asked Questions
Related Tutorials
Written by KotlinGuide Editorial Team ยท Reviewed by KotlinGuide Technical Review