Ad space (banner)
๐ŸŽฏKotlin Lessons
Lesson 9 / 68

Classes (Object-Oriented Programming)

In this lesson you will learn the basics of object-oriented programming with Kotlin classes, so you can group data that shares the same characteristics. This is for anyone searching for "Kotlin class how to use".

class defines a class. Because Kotlin lets you write the constructor parameters straight after the class name, a class definition is far more concise than in Java.

The sample code defines the properties and the constructor together in the single line class Animal(val name: String, val sound: String), and builds a message in the speak() method. Notice how Animal("Dog", "Woof") creates an instance.

A common stumbling block for beginners is how different this is from a Java class definition. Declaring the fields, defining the constructor, and generating the getters all happen in one line, and that concision can be disorienting at first.

In real-world development there is also the even more convenient data class, which is used constantly in Android app development.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Kotlin directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)