Labs ICT
โญ Pro Login

Classes & Objects

Kotlin is object-oriented from the ground up. If you've used Java, C#, or Python classes, you'll feel right at home. But Kotlin adds some nice sugar to make classes cleaner and more expressive.

Your first class

A class is a blueprint for creating objects. You define one with the class keyword, and you can pack properties right into the constructor.


class Person(val name: String, var age: Int)

fun main() {
  val person = Person("Alice", 25)
  println("${person.name} is ${person.age} years old")
}
    

Notice how the properties (name and age) are declared right in the constructor. val means read-only, var means you can change it later.

Try it Yourself โ†’

Creating objects

You don't need the new keyword in Kotlin. Just call the class like a function: Person("Alice", 25). Clean, right?


class Car(val brand: String, var year: Int)

fun main() {
  val myCar = Car("Toyota", 2020)
  println(myCar.brand)
  myCar.year = 2022
  println(myCar.year)
}
    

Once you have an object, use the dot notation to access or modify its properties.

Try it Yourself โ†’

Class body

You can also add functions (methods) inside the class body to give your objects behavior.


class Dog(val name: String) {
  fun bark() = println("$name says woof!")
}

fun main() {
  val dog = Dog("Buddy")
  dog.bark()
}
    

Every Dog object knows how to bark. The method can access the property name directly.

Try it Yourself โ†’

๐Ÿงช Quick Quiz

What keyword creates a class in Kotlin?