Kotlin Tutoial

Basics

Control Flow

Array & String

Functions

Collections

OOPs Concept

Exception Handling

Null Safety

Regex & Ranges

Java Interoperability

Miscellaneous

Android

Kotlin Constructor

In Kotlin, constructors are a fundamental part of classes and are used to initialize the object. Kotlin offers two types of constructors: primary and secondary.

1. Primary Constructor:

The primary constructor is a part of the class header and is declared after the class name.

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

In the above example, the primary constructor has two parameters: name and age. The properties name and age are declared and initialized using the primary constructor.

2. Constructor Body:

If you want to add some additional initialization logic, you can use an init block. This block is executed when the class is instantiated:

class Person(val name: String, var age: Int) {
    init {
        println("Person named $name of age $age is created.")
    }
}

3. Secondary Constructors:

A class can also have one or more secondary constructors. These constructors are prefixed with the constructor keyword:

class Person(val name: String) {
    var age: Int = 0

    constructor(name: String, age: Int) : this(name) {
        this.age = age
    }
}

In this example, Person has a primary constructor and a secondary constructor. The secondary constructor needs to delegate to the primary constructor using the this keyword.

4. Default and Named Arguments:

Kotlin supports default arguments, allowing you to skip some constructor parameters if they have default values:

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

val p1 = Person("Alice")        // age will be 0
val p2 = Person("Bob", 25)

Additionally, you can use named arguments to make your code more readable:

val p3 = Person(name = "Charlie", age = 30)

5. Private Constructors:

If you don't want your class to be instantiated from outside the class, you can mark the constructor as private:

class Singleton private constructor() {
    companion object {
        val instance = Singleton()
    }
}

In this example, the Singleton class can't be instantiated directly. Instead, an instance is provided through the companion object.

6. No-Arg Constructors:

If you don't declare any constructor, the compiler provides a default parameterless constructor for you:

class Empty

val e = Empty()   // Calls the no-arg constructor

Conclusion:

Constructors in Kotlin are designed to be more concise and flexible than in many other languages. By understanding the primary and secondary constructors, as well as features like default and named arguments, you can create more readable and efficient initialization logic for your classes.

  1. Primary constructor in Kotlin: The primary constructor is declared in the class header.

    class Person(val name: String, val age: Int)
    
  2. Secondary constructors in Kotlin: Secondary constructors are defined in the class body using the constructor keyword.

    class Person {
        constructor(name: String, age: Int) {
            // Initialization code
        }
    }
    
  3. Initializing properties in Kotlin constructors: Properties can be initialized directly in the primary constructor.

    class Person(val name: String, var age: Int = 18)
    
  4. Default values for constructor parameters in Kotlin: You can provide default values for constructor parameters.

    class Person(val name: String, var age: Int = 18)
    
  5. Constructor overloading in Kotlin: Multiple constructors with different parameter sets can be defined.

    class Person {
        constructor(name: String, age: Int) { /* ... */ }
        constructor(name: String) : this(name, 18) { /* ... */ }
    }
    
  6. Visibility modifiers in Kotlin constructors: Constructors can have visibility modifiers like private, protected, or internal.

    class Person private constructor(val name: String, var age: Int)
    
  7. Init block in Kotlin constructor: The init block is executed during object initialization.

    class Person(val name: String, var age: Int) {
        init {
            println("Person initialized with name: $name, age: $age")
        }
    }
    
  8. Using constructors in data classes in Kotlin: Data classes automatically generate constructors for their properties.

    data class Person(val name: String, var age: Int)
    
  9. Constructors and inheritance in Kotlin: Subclasses must call the primary constructor or secondary constructor of the superclass.

    open class Animal(val name: String)
    
    class Dog(name: String, val breed: String) : Animal(name)
    
  10. Accessing constructor parameters in Kotlin: Constructor parameters can be accessed directly in the class body.

    class Person(val name: String, var age: Int) {
        fun printDetails() {
            println("Name: $name, Age: $age")
        }
    }
    
  11. Named parameters in Kotlin constructors: Named parameters allow you to pass values to a constructor in any order.

    class Person(val name: String, var age: Int)
    
    val person = Person(age = 25, name = "Alice")