Kotlin Constructor
A constructor in Kotlin is a special function that is used to initialize objects of a class. In this tutorial, we'll discuss the syntax, examples, output, explanation, use, important points, and summary of Kotlin constructors.
Syntax
The syntax for creating a constructor in Kotlin is as follows:
class MyClass {
constructor() { // Primary constructor
// initialization code
}
constructor(name: String) { // Secondary constructor
// initialization code
}
}
In the above example, we have created two constructors for the class MyClass
. The first constructor is the primary constructor that has no parameters, and the second constructor is a secondary constructor that takes a single parameter of type String.
Example
Let's create a simple example to illustrate how constructors work in Kotlin:
class Person(name: String, age: Int) {
init {
println("Name: $name")
println("Age: $age")
}
}
fun main(args: Array<String>) {
val person = Person("John", 25)
}
In the above example, we have created a class Person
with two constructor parameters: name
and age
. The init
block is called when an object is created, and it initializes the object by printing out the name
and age
properties.
The main
function creates a new object of the Person
class with the name "John" and age 25. When the object is created, the init
block is executed and the output is:
Name: John
Age: 25
Output
The output of the example code is:
Name: John
Age: 25
Explanation
A constructor is a special member function of a class that is called when an object of the class is created. The primary constructor is part of the class header and can take optional parameters. The secondary constructor is defined using the constructor
keyword and can have different parameter lists.
The init
block initializes the properties of the object and is called after the object is created, but before it is returned to the caller.
Use
Constructors are used to initialize the object of a class and provide initial values to the properties of the class. You can define multiple constructors for a class, and each constructor can have a different parameter list or initialization code.
Important Points
- The primary constructor is defined in the class header and is called when an object is created.
- Secondary constructors are defined using the
constructor
keyword and can have different parameter lists. - The
init
block is used to initialize properties of an object and is called after the object is created. - You can define multiple constructors for a class.
Summary
In this tutorial, we discussed Kotlin constructors, including their syntax, examples, output, explanation, use, important points, and summary. With this knowledge, you can create constructors for your Kotlin classes and initialize objects with ease.