What is a class in Kotlin?

Overview

A class is a blueprint for objects that have similar properties.

In Kotlin, a class is declared using the class keyword, followed by the class name, an optional constructor, and the class body enclosed within curly brackets. All the properties and the member functions of the class are defined inside the class body.

Syntax

class className {
// body
}
Class declaration syntax without a constructor in Kotlin
class className constructor(){
// body
}
Class declaration syntax with a constructor in Kotlin

If we don't specify the constructor, the compiler will generate an empty constructor on its own.

Example

Let's see an example of a Kotlin class in the code snippet below:

// class declaration
class example {
var name: String = "Shubham"
var age: Int = 22
fun getNameAndAge() {
// body
}
}

Explanation

  • Line 2: We declare a class, example.
  • Line 3–4: We declare two class properties and assign them some value.
  • Line 6: We define a member function, getNameAndAge().
Properties in Kotlin must be either initialized or declared as abstract.

Free Resources