Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

kotlin
communitycreator

What is a class in Kotlin?

Shubham Singh Kshatriya

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
  }
}

A class example in Kotlin

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.

RELATED TAGS

kotlin
communitycreator

CONTRIBUTOR

Shubham Singh Kshatriya
RELATED COURSES

View all Courses

Keep Exploring