Kotlin / Object-Oriented Programming in Kotlin

Working with Constructors and Initializers

In this tutorial, you'll learn about constructors and initializers in Kotlin. We will explore how to define constructors and how to initialize objects.

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Covers OOP concepts like classes, objects, inheritance, and polymorphism.

Sure, here is the tutorial:

Working with Constructors and Initializers in Kotlin

1. Introduction

In this tutorial, we'll delve into the world of constructors and initializers in Kotlin. We'll learn how to define constructors, how to initialize objects, and understand their importance in object-oriented programming.

Goals of this tutorial:

  • Understand the concept of constructors and initializers in Kotlin.
  • Learn to define constructors and initialize objects.

What you'll learn:

  • The basic and secondary constructors in Kotlin.
  • How to use initializers in Kotlin.
  • Best practices when working with constructors and initializers.

Prerequisites:

  • Basic understanding of Kotlin syntax and object-oriented programming.
  • An installed version of Kotlin to run the code examples.

2. Step-by-Step Guide

In Kotlin, a constructor is a special member function that is used to initialize the properties of a class. There are two types of constructors in Kotlin: primary and secondary.

The primary constructor is part of the class header. It goes after the class name.

A secondary constructor is defined inside the class body. It starts with the constructor keyword.

An initializer block is part of a class body. It's prefixed by the init keyword. It's executed when the class is instantiated, allowing you to initialize the class properties.

3. Code Examples

Example 1: Primary Constructor

class Person(name: String, age: Int) { // primary constructor
    // properties
    var name: String = name
    var age: Int = age

    // initializer block
    init {
        println("Person is initialized with parameters: Name = $name, Age = $age")
    }
}

fun main() {
    val person1 = Person("John", 20) // creates Person object
}

Explanations:

  • class Person(name: String, age: Int): This is the primary constructor.
  • var name: String = name and var age: Int = age: These are properties initialized with constructor parameters.
  • init block is used for initialization.

Expected output:

Person is initialized with parameters: Name = John, Age = 20

Example 2: Secondary Constructor

class Person {
    var name: String
    var age: Int

    // secondary constructor
    constructor(name: String, age: Int) {
        this.name = name
        this.age = age
        println("Person is initialized with parameters: Name = $name, Age = $age")
    }
}

fun main() {
    val person2 = Person("Jane", 25) // creates Person object
}

Explanations:

  • constructor(name: String, age: Int): This is the secondary constructor.
  • this.name = name and this.age = age: This is how we initialize properties with constructor parameters in a secondary constructor.

Expected output:

Person is initialized with parameters: Name = Jane, Age = 25

4. Summary

In this tutorial, we learned about primary and secondary constructors in Kotlin, as well as initializer blocks. We understood how they are used to initialize objects and properties.

Next steps for learning:

  • Look into more complex examples using constructors and initializers.
  • Learn about constructor chaining in Kotlin.

Additional resources:

5. Practice Exercises

Exercise 1: Create a class Student with primary constructor having properties rollNo and name.

Exercise 2: Modify the Student class to have a secondary constructor which also includes age property.

Solution and Explanation:

Exercise 1 Solution:

class Student(rollNo: Int, name: String) {
    var rollNo: Int = rollNo
    var name: String = name

    init {
        println("Student is initialized with parameters: Roll No = $rollNo, Name = $name")
    }
}

Exercise 2 Solution:

class Student {
    var rollNo: Int
    var name: String
    var age: Int

    constructor(rollNo: Int, name: String, age: Int) {
        this.rollNo = rollNo
        this.name = name
        this.age = age
        println("Student is initialized with parameters: Roll No = $rollNo, Name = $name, Age = $age")
    }
}

In these exercises, you have practiced creating classes with primary and secondary constructors. Keep practicing to become more proficient.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Timestamp Converter

Convert timestamps to human-readable dates.

Use tool

Age Calculator

Calculate age from date of birth.

Use tool

Fake User Profile Generator

Generate fake user profiles with names, emails, and more.

Use tool

PDF to Word Converter

Convert PDF files to editable Word documents.

Use tool

Image Converter

Convert between different image formats.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help