How to Create A Class In Kotlin?

9 minutes read

To create a class in Kotlin, you need to follow a simple syntax. Here's the basic structure of a class in Kotlin:

1
2
3
class ClassName {
    // Properties (variables) and functions go here
}


The class declaration starts with the keyword class, followed by the name of the class. Inside the curly braces, you can define the properties (variables) and functions of the class.


Properties can be defined using the var or val keywords, where var indicates a mutable variable and val indicates an immutable (read-only) variable. For example:

1
2
3
4
class Person {
    var name: String = ""
    val age: Int = 0
}


In the above example, name is a mutable variable of type String, and age is an immutable variable of type Int.


Functions can be defined within the class as well. Here's an example of a class with a function:

1
2
3
4
5
class Calculator {
    fun add(num1: Int, num2: Int): Int {
        return num1 + num2
    }
}


In the above example, add is a function that takes two parameters num1 and num2 of type Int and returns their sum.


You can create instances of the class by using the ClassName() syntax, and then access its properties or call its functions using the dot notation. Here's an example:

1
2
3
4
5
6
val person = Person()
person.name = "John"
person.age = 25 // This will give a compilation error as age is read-only

val calculator = Calculator()
val sum = calculator.add(5, 3) // Returns 8


That's a brief overview of how to create a class in Kotlin and define properties and functions within it.

Best Kotlin Books to Read in 2024

1
Atomic Kotlin

Rating is 5 out of 5

Atomic Kotlin

2
Kotlin in Action

Rating is 4.9 out of 5

Kotlin in Action

3
Head First Kotlin: A Brain-Friendly Guide

Rating is 4.8 out of 5

Head First Kotlin: A Brain-Friendly Guide

4
Kotlin Programming: The Big Nerd Ranch Guide (Big Nerd Ranch Guides)

Rating is 4.7 out of 5

Kotlin Programming: The Big Nerd Ranch Guide (Big Nerd Ranch Guides)

5
Kotlin Cookbook: A Problem-Focused Approach

Rating is 4.6 out of 5

Kotlin Cookbook: A Problem-Focused Approach

6
Java to Kotlin: A Refactoring Guidebook

Rating is 4.5 out of 5

Java to Kotlin: A Refactoring Guidebook

7
Programming Kotlin: Create Elegant, Expressive, and Performant JVM and Android Applications

Rating is 4.4 out of 5

Programming Kotlin: Create Elegant, Expressive, and Performant JVM and Android Applications

8
Advanced Kotlin (Kotlin for Developers Book 4)

Rating is 4.3 out of 5

Advanced Kotlin (Kotlin for Developers Book 4)


How to implement an interface in a Kotlin class?

To implement an interface in a Kotlin class, you need to use the : InterfaceName syntax after the class name. Here is an example implementation of an interface in a Kotlin class:

1
2
3
4
5
6
7
8
9
interface MyInterface {
    fun myFunction()
}

class MyClass : MyInterface {
    override fun myFunction() {
        println("Implementing myFunction in MyClass")
    }
}


In the above example, the MyClass implements the MyInterface by using the : MyInterface syntax after the class name. It also overrides the myFunction method defined in the interface.


You can then create an instance of the MyClass and call the myFunction method as shown below:

1
2
3
4
fun main() {
    val myClass = MyClass()
    myClass.myFunction()
}


This will output: "Implementing myFunction in MyClass"


How to create inner classes in Kotlin?

In Kotlin, you can create inner classes using the inner keyword. An inner class is a class that is nested inside another class and has access to its outer class's members. Here's how you can create inner classes in Kotlin:

1
2
3
4
5
6
7
8
9
class Outer {
    private val outerProperty = "Outer Property"

    inner class Inner {
        fun innerMethod() {
            println(outerProperty) // Accessing outer class property
        }
    }
}


In the example above, the Inner class is an inner class of the Outer class. It has access to the outerProperty property of the Outer class.


To create an instance of the inner class, you need an instance of the outer class. Here's how you can do it:

1
2
3
val outer = Outer()
val inner = outer.Inner() // Creating an instance of the inner class
inner.innerMethod() // Accessing inner class method


In this example, we create an instance of the Outer class and then use that instance to create an instance of the Inner class. Finally, we call the innerMethod() of the Inner class.


Note that inner classes hold a reference to an instance of their outer class. If you want to create a nested class without the reference to the outer class, you can use the nested keyword instead of inner.


How to create a sealed class in Kotlin?

To create a sealed class in Kotlin, follow these steps:

  1. Define the sealed class using the sealed keyword. Sealed classes are used to represent restricted class hierarchies where all the subclasses are known. They are useful when you have a fixed set of subclasses and want to enforce that no other subclasses can be added.
1
2
3
sealed class MySealedClass {
    // subclasses will be defined here
}


  1. Inside the sealed class, define the subclasses using the class keyword. Subclasses of a sealed class must be declared within the same file as the sealed class itself (or in an extending class).
1
2
3
4
5
sealed class MySealedClass {
    class Subclass1 : MySealedClass()
    class Subclass2 : MySealedClass()
    // additional subclasses
}


  1. Optionally, you can also define object expressions as subclasses of the sealed class.
1
2
3
4
5
6
7
8
sealed class MySealedClass {
    class Subclass1 : MySealedClass()
    class Subclass2 : MySealedClass()

    object Subclass3 : MySealedClass() {
        fun someFunction() {}
    }
}


Note: The subclasses of a sealed class can have their own properties and methods.


Now you have created a sealed class MySealedClass with subclasses Subclass1, Subclass2, and an object expression Subclass3.

Facebook Twitter LinkedIn Whatsapp Pocket

Related Posts:

To implement Parcelable in Kotlin for Android development, follow these steps:Open your Kotlin data class or model class that you want to make Parcelable. Add the Parcelable interface to your class declaration: data class ExampleModel(...) : Parcelable { // cl...
The Kotlin Standard Library functions are a set of utility functions that come built-in with the Kotlin programming language. These functions provide convenient ways to perform common tasks when working with different types of data.To use the Kotlin Standard L...
Creating custom views and view bindings in Kotlin for Android allows you to build unique UI elements and bind them to your application logic. Here's a step-by-step guide on how to do it:First, create a new Kotlin file for your custom view. This file will c...