How to Create And Use Classes In Kotlin?

13 minutes read

In Kotlin, classes are the building blocks of object-oriented programming. They encapsulate data and behavior, allowing you to define custom types. Here's a brief explanation of how to create and use classes in Kotlin:


To create a class, use the "class" keyword followed by the class name. By convention, class names usually start with an uppercase letter. For example:

1
2
3
class MyClass {
    // class body
}


Inside the class body, you can define properties, functions, and other elements. Properties are declared using the "val" or "var" keywords. "val" properties are read-only (immutable), whereas "var" properties are mutable. For example:

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


You can also define functions inside a class. Functions can be either member functions or static functions. Member functions belong to an instance of a class, while static functions belong to the class itself. For example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Calculator {
    fun add(a: Int, b: Int): Int {
        return a + b
    }
    
    companion object {
        fun multiply(a: Int, b: Int): Int {
            return a * b
        }
    }
}


To create an instance of a class, use the constructor. In Kotlin, the primary constructor is declared in the class header itself. You can also define secondary constructors if needed. For example:

1
2
3
4
5
class Rectangle(val width: Int, val height: Int) {
    // class body
}

val myRectangle = Rectangle(10, 5)


To access the properties and functions of a class, use the dot notation. For example:

1
2
3
println(myRectangle.width)
println(myRectangle.height)
println(myRectangle.calculateArea())


Inheritance is also supported in Kotlin, allowing you to create subclasses that inherit properties and functions from a superclass. The "open" keyword is used to make a class inheritable. For example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
open class Shape {
    open fun calculateArea(): Double {
        // calculate area logic
    }
}

class Circle(val radius: Double) : Shape() {
    override fun calculateArea(): Double {
        // calculate circle area logic
    }
}


That's a basic overview of creating and using classes in Kotlin. Classes provide the foundation for defining objects and implementing various features of object-oriented programming.

Best Kotlin Books to Read in 2024

1
Atomic Kotlin

Rating is 5 out of 5

Atomic Kotlin

2
Head First Android Development: A Learner's Guide to Building Android Apps with Kotlin

Rating is 4.9 out of 5

Head First Android Development: A Learner's Guide to Building Android Apps with Kotlin

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

Rating is 4.8 out of 5

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

4
Kotlin in Action

Rating is 4.7 out of 5

Kotlin in Action

5
Kotlin Design Patterns and Best Practices: Build scalable applications using traditional, reactive, and concurrent design patterns in Kotlin, 2nd Edition

Rating is 4.6 out of 5

Kotlin Design Patterns and Best Practices: Build scalable applications using traditional, reactive, and concurrent design patterns in Kotlin, 2nd Edition

6
Head First Kotlin: A Brain-Friendly Guide

Rating is 4.5 out of 5

Head First Kotlin: A Brain-Friendly Guide

7
Kotlin Cookbook: A Problem-Focused Approach

Rating is 4.4 out of 5

Kotlin Cookbook: A Problem-Focused Approach

8
How to Build Android Apps with Kotlin: A practical guide to developing, testing, and publishing your first Android apps, 2nd Edition

Rating is 4.3 out of 5

How to Build Android Apps with Kotlin: A practical guide to developing, testing, and publishing your first Android apps, 2nd Edition

9
Modern Android 13 Development Cookbook: Over 70 recipes to solve Android development issues and create better apps with Kotlin and Jetpack Compose

Rating is 4.2 out of 5

Modern Android 13 Development Cookbook: Over 70 recipes to solve Android development issues and create better apps with Kotlin and Jetpack Compose

10
Java to Kotlin: A Refactoring Guidebook

Rating is 4.1 out of 5

Java to Kotlin: A Refactoring Guidebook


How to invoke methods of a class in Kotlin?

To invoke methods of a class in Kotlin, you need to follow these steps:

  1. Create an instance of the class using the new keyword followed by the class name and parentheses. Kotlin allows omitting the new keyword when creating instances of classes. val obj = ClassName()
  2. Once you have an instance of the class, you can use the dot (.) operator to access its methods and properties. obj.methodName()


Here's an example that demonstrates invoking methods of a class:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class MyClass {
    fun sayHello() {
        println("Hello!")
    }

    fun addNumbers(a: Int, b: Int): Int {
        return a + b
    }
}

fun main() {
    val obj = MyClass()
    obj.sayHello()
    
    val sum = obj.addNumbers(5, 10)
    println("Sum: $sum")
}


Output:

1
2
Hello!
Sum: 15


In the above example, we create an instance of the MyClass using val obj = MyClass(). Then we invoke the sayHello method and the addNumbers method using obj.sayHello() and obj.addNumbers(5, 10) respectively.


How to define static properties in a class in Kotlin?

In Kotlin, static properties are defined using the "companion object". The companion object is an object that is associated with the class and can access its private members.


To define a static property, you need to define it inside the companion object. Here's an example of how to define a static property in a class:

1
2
3
4
5
class MyClass {
   companion object {
      val staticProperty: Int = 10
   }
}


In the above example, staticProperty is a static property defined inside the companion object of the MyClass class. It can be accessed using the class name, like MyClass.staticProperty.


How to use data classes in Kotlin?

To use data classes in Kotlin, you need to follow these steps:

  1. Define a class with the data keyword before the class keyword.
  2. Add the properties that you want to include in the data class constructor.
  3. (Optional) Provide default values for the properties in the data class constructor.
  4. (Optional) Add functions or additional properties if needed.


Here is an example of using data classes in Kotlin:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
data class Person(val name: String, val age: Int)

fun main() {
    val person1 = Person("John", 25)
    val person2 = Person("Jane", 30)
    
    println(person1) // Output: Person(name=John, age=25)
    println(person2) // Output: Person(name=Jane, age=30)

    println(person1 == person2) // Output: false (data classes automatically implement equals() method)
    println(person1.hashCode()) // Output: 785107505 (data classes automatically implement hashCode() method)
    
    val person3 = person1.copy(age = 26) // Create a copy with updated age
    println(person3) // Output: Person(name=John, age=26)
}


In the above example, Person is a data class with two properties: name and age. The data class automatically generates useful methods such as toString(), equals(), and hashCode().


You can create instances of data classes using the regular class constructor syntax. Data classes also provide a copy() function that allows you to create a copy of an instance with some properties updated.


How to create methods in a class in Kotlin?

In Kotlin, you can create methods in a class by declaring functions inside the class body. Here's an example of how to create methods in a class:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class MyClass {
    // method without return type
    fun greet(name: String) {
        println("Hello, $name!")
    }

    // method with return type
    fun addNumbers(a: Int, b: Int): Int {
        return a + b
    }
}


In the above example, greet() is a method that takes a String parameter name and prints a greeting message. addNumbers() is a method that takes two Int parameters a and b and returns their sum as an Int.


To call these methods, you can create an instance of the class and use the dot notation:

1
2
3
4
5
6
7
8
fun main() {
    val obj = MyClass()
    
    obj.greet("John") // Hello, John!
    
    val sum = obj.addNumbers(5, 3)
    println(sum) // 8
}


In the main() function, we create an instance of MyClass called obj. To call greet(), we use obj.greet("John"). To call addNumbers(), we pass the arguments and assign the returned value to sum. Finally, we print the value of sum.


How to access properties of a class in Kotlin?

In Kotlin, you can access the properties of a class using dot notation.


For example, consider the following class:

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


To access the properties of an object of this class, you can use the dot notation as shown below:

1
2
3
val person = Person("John", 30)
println(person.name) // Accessing a read-only property
person.age = 40 // Accessing a mutable property


In this example, name is a read-only property, so you can only access its value. On the other hand, age is a mutable property, so you can access and modify its value.


You can also access the properties of a class inside a class member function using the this keyword:

1
2
3
4
5
6
class Person(val name: String, var age: Int) {
    fun printPersonInfo() {
        println("Name: ${this.name}")
        println("Age: ${this.age}")
    }
}


In this example, this.name refers to the name property of the current object, and this.age refers to the age property.


What are interfaces in Kotlin?

In Kotlin, interfaces are similar to those in other programming languages. They define a contract or a set of rules that a class must follow.


An interface can contain abstract methods (methods without an implementation) as well as default methods (methods with a default implementation). Classes that implement an interface must provide an implementation for all the abstract methods defined in the interface.


One class can implement multiple interfaces, enabling it to provide different behaviors defined by each interface. This allows for better modularity and code reuse. Interfaces in Kotlin can also contain properties, without backing fields.


To implement an interface in Kotlin, a class needs to use the "implements" keyword followed by the interface's name. Unlike Java, Kotlin uses the "interface" keyword to declare an interface.


Here's an example that demonstrates the usage of interfaces in Kotlin:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
interface Printable {
    fun print()
}

class Document : Printable {
    override fun print() {
        println("Printing the document...")
    }
}

fun main() {
    val doc = Document()
    doc.print() // Output: Printing the document...
}


In this example, the Printable interface declares a single abstract method print(). The Document class implements the Printable interface and provides an implementation for the print() method. Finally, in the main() function, we create an instance of Document and call its print() method.

Facebook Twitter LinkedIn Whatsapp Pocket

Related Posts:

In Kotlin, extension functions allow you to add new functionality to existing classes without modifying their source code. They provide a way to extend the behavior of classes from external libraries or even built-in classes. Here is how you can define and use...
In Kotlin, enums are a type that allows you to define a collection of constant values. They are used to represent a fixed number of possible values for a property or a variable. Enum classes make your code more readable and help to avoid errors by restricting ...
To run shell tools from a Kotlin script, you can use the ProcessBuilder class in Kotlin's standard library. Here's a brief explanation of how you can achieve it:Import the necessary classes: import java.io.BufferedReader import java.io.