Kotlin - Constructors (Primary and Secondary)

Constructors (Primary and Secondary) in Kotlin

In Kotlin, constructors are special member functions invoked when an object is instantiated. They initialize class properties and perform setup operations. Kotlin offers two types of constructors: Primary Constructors and Secondary Constructors.

1. Primary Constructors

The primary constructor is part of the class header and provides a concise way to initialize class properties.

1.1 Syntax

class Person constructor(name: String, age: Int) {
    // class body
}

If the primary constructor doesn't have annotations or visibility modifiers, the constructor keyword can be omitted:

class Person(name: String, age: Int) {
    // class body
}

1.2 Property Initialization

Properties can be initialized directly in the primary constructor:

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

Here, name is a read-only property, and age is mutable.

1.3 Initializer Blocks

The primary constructor cannot contain code. Initialization code can be placed in init blocks:

class Person(name: String) {
    val upperName: String

    init {
        upperName = name.uppercase()
    }
}

Multiple init blocks are executed in the order they appear in the class body.

1.4 Default Parameter Values

Primary constructor parameters can have default values:

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

This allows instantiation without providing all arguments:

val person = Person()
val personWithName = Person("Alice")

2. Secondary Constructors

Secondary constructors are defined using the constructor keyword inside the class body. They provide alternative ways to instantiate a class.

2.1 Syntax

class Person {
    var name: String
    var age: Int

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

2.2 Delegation to Primary Constructor

If a class has a primary constructor, each secondary constructor must delegate to it using this:

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

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

2.3 Multiple Secondary Constructors

A class can have multiple secondary constructors, each providing different initialization logic:

class Person {
    var name: String
    var age: Int

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

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

3. Combining Primary and Secondary Constructors

It's possible to use both primary and secondary constructors in the same class. Secondary constructors must delegate to the primary constructor:

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

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

4. Visibility Modifiers

Constructors can have visibility modifiers to control access:

class Person private constructor(val name: String) {
    // class body
}

This restricts instantiation of the class from outside.

5. Constructor Overloading

Kotlin supports constructor overloading through secondary constructors:

class Person {
    var name: String
    var age: Int

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

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

6. Best Practices

  • Use primary constructors for simple initialization.
  • Use secondary constructors when additional initialization logic is required.
  • Prefer default parameter values over multiple constructors when possible.
  • Keep initialization logic concise and clear.

Kotlin's constructor system provides flexibility and conciseness in object initialization. Understanding the differences and use-cases for primary and secondary constructors allows developers to write more readable and maintainable code.

Beginner 5 Hours

Constructors (Primary and Secondary) in Kotlin

In Kotlin, constructors are special member functions invoked when an object is instantiated. They initialize class properties and perform setup operations. Kotlin offers two types of constructors: Primary Constructors and Secondary Constructors.

1. Primary Constructors

The primary constructor is part of the class header and provides a concise way to initialize class properties.

1.1 Syntax

class Person constructor(name: String, age: Int) { // class body }

If the primary constructor doesn't have annotations or visibility modifiers, the constructor keyword can be omitted:

class Person(name: String, age: Int) { // class body }

1.2 Property Initialization

Properties can be initialized directly in the primary constructor:

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

Here, name is a read-only property, and age is mutable.

1.3 Initializer Blocks

The primary constructor cannot contain code. Initialization code can be placed in init blocks:

class Person(name: String) { val upperName: String init { upperName = name.uppercase() } }

Multiple init blocks are executed in the order they appear in the class body.

1.4 Default Parameter Values

Primary constructor parameters can have default values:

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

This allows instantiation without providing all arguments:

val person = Person() val personWithName = Person("Alice")

2. Secondary Constructors

Secondary constructors are defined using the constructor keyword inside the class body. They provide alternative ways to instantiate a class.

2.1 Syntax

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

2.2 Delegation to Primary Constructor

If a class has a primary constructor, each secondary constructor must delegate to it using

this:

class Person(val name: String) { var age: Int = 0 constructor(name: String, age: Int) : this(name) { this.age = age } }

2.3 Multiple Secondary Constructors

A class can have multiple secondary constructors, each providing different initialization logic:

class Person { var name: String var age: Int constructor(name: String) { this.name = name this.age = 0 } constructor(name: String, age: Int) { this.name = name this.age = age } }

3. Combining Primary and Secondary Constructors

It's possible to use both primary and secondary constructors in the same class. Secondary constructors must delegate to the primary constructor:

class Person(val name: String) { var age: Int = 0 constructor(name: String, age: Int) : this(name) { this.age = age } }

4. Visibility Modifiers

Constructors can have visibility modifiers to control access:

class Person private constructor(val name: String) { // class body }

This restricts instantiation of the class from outside.

5. Constructor Overloading

Kotlin supports constructor overloading through secondary constructors:

class Person { var name: String var age: Int constructor(name: String) { this.name = name this.age = 0 } constructor(name: String, age: Int) { this.name = name this.age = age } }

6. Best Practices

  • Use primary constructors for simple initialization.
  • Use secondary constructors when additional initialization logic is required.
  • Prefer default parameter values over multiple constructors when possible.
  • Keep initialization logic concise and clear.

Kotlin's constructor system provides flexibility and conciseness in object initialization. Understanding the differences and use-cases for primary and secondary constructors allows developers to write more readable and maintainable code.

Related Tutorials

Frequently Asked Questions for Kotlin

Companion objects hold static members, like Java’s static methods, in Kotlin classes.

A concise way to define anonymous functions using { parameters -> body } syntax.

Kotlin prevents null pointer exceptions using nullable (?) and non-null (!!) type syntax.

Inline functions reduce overhead by inserting function code directly at call site.

JetBrains, the makers of IntelliJ IDEA, developed Kotlin and released it in 2011.

Allows non-null variables to be initialized after declaration (used with var only).

val is immutable (read-only), var is mutable (can change value).

Compiler automatically determines variable types, reducing boilerplate code.

A data class automatically provides equals(), hashCode(), toString(), and copy() methods.

A function that takes functions as parameters or returns them.

Kotlin is a modern, statically typed language that runs on the Java Virtual Machine (JVM).

They add new methods to existing classes without modifying their source code.

It allows unpacking data class properties into separate variables.

== checks value equality; === checks reference (memory) equality.


apply is a scope function to configure an object and return it.

A class that restricts subclassing, useful for representing restricted class hierarchies.

Coroutines enable asynchronous programming by suspending and resuming tasks efficiently.

Functions can define default values for parameters, avoiding overloads.

Kotlin offers concise syntax, null safety, and modern features not found in Java.

Kotlin automatically casts variables to appropriate types after type checks.

Use the object keyword to create a singleton.

Calls a method only if the object is non-null.

Yes, Kotlin supports backend development using frameworks like Ktor and Spring Boot.

Data structures like List, Set, and Map, supporting functional operations.

line

Copyrights © 2024 letsupdateskills All rights reserved