Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

Learn kotlin Constructors


Constructors in Kotlin are special functions that are automatically called when an object of a class is created. They are used to initialize properties and perform any necessary setup for the object. Here's a simple explanation with an example:

Primary Constructor

A primary constructor is declared in the class header. It can include property declarations.

class Person(val name: String, var age: Int) {
fun speak() {
println("Hello, my name is $name and I am $age years old.")
}
}

In this example:

Secondary Constructors

Secondary constructors are additional constructors defined within the class using the constructor keyword. They provide alternative ways to create objects.

class Person {
var name: String = ""
var age: Int = 0

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

fun speak() {
println("Hello, my name is $name and I am $age years old.")
}
}

In this example:

Creating Objects with Constructors

You can create objects of a class using either the primary or secondary constructors.

fun main() {
// Using the primary constructor
val person1 = Person("Alice", 30)

// Using the secondary constructor
val person2 = Person("Bob", 25)

person1.speak() // Output: Hello, my name is Alice and I am 30 years old.
person2.speak() // Output: Hello, my name is Bob and I am 25 years old.
}

In this example:

Conclusion

Constructors in Kotlin are used to initialize properties of objects when they are created. They can be primary or secondary, providing flexibility in object creation. Understanding constructors is essential for creating and initializing objects in Kotlin.

Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java