Recent Posts
- jQuery attrAugust 12, 2021
- jQuery mouseenterAugust 9, 2021
- jQuery ToggleclassAugust 6, 2021
- jQuery attr
A constructor is a special member function which is invoked when a class object is generated primarily for the initialization of variables or properties. A class needs to have a constructor and if we don’t declare a constructor then a default constructor is created by the compiler.
There are two types of Constructor:
A Kotlin class can also have a limit of one main constructor, and one or more secondary builders. The main builder initializes the class while using the secondary builder to initialize the class and add some additional logic.
Below are the examples of Kotlin Constructors:
Primary Constructor are also initialized in the class header, using the constructor Keyword. Here is a program using Primary Constructor.
fun main(args: Array<String>)
{
val add = Add (3,7)
println(“Sum will be: ${add.c}”)
}
//now the Primary constructor will be used
class Add constructor(a: Int, b:Int)
{
var c = a+b;
}
Primary Constructor and Initializer Blocks. The primary constructor has a syntax that is limited and cannot contain any code it. So to insert the initialization code an initializer block is used with init, example:
fun main(args: Array<String>) {
val person1 = NAme(“kotlin”, 31)
}
class NAme(fName: String, yourAge: Int) {
valnewName: String
var age: Int
// initializer block – This block initialize the code written in the constructor
init {
newName= fName.capitalize()
age = yourAge
println(“First Name = $newName”)
Explanation: In the above program we have used 2 parameters Name andyourAgeinside the parenthesis which accepts the values kotlin and 31 respectively when person1 object is created. HoweverfName and personAgeare used without initialization like var and val and they both are also not properties of the Person class.
And moreover, there is a function called uppercase which changes the character value from lower case to uppercase.
As explained before, Kotlin will have one or two side builders. Secondary constructors allow the initialization of variables and also allow the class to give any rationale. They are prefix with the keyword for the constructor.
Kotlin also allows the creation of your class of one or more secondary builders. This secondary builder is generated using the keyword”constructor”. It is required whenever you want to create more than one builder in Kotlin or whenever you want to include more logic in the primary builder and you can’t do that because some other class can call the primary constructor. below is the example:
fun main(args: Array<String>) {
valZambo = Zambo (“Kotlin Learner “, 31)
print(“${Zambo.message}”+”${ Zambo.firstName}”+
“Welcome to Kotlin Constructor, Here is your Age-${ Zambo.age}”)
}
class Zambo (valfirstName: String, var age: Int) {
val message: String = “Hello! “
constructor(name : String , age :Int ,message :String):this(name,age) {
}
}
Explanation: In the above program values have been declare under Zambo and then used inside the code which in turn prints the output by concatenating the different variables and values inside the code.
Let’s see a few more examples of both Primary and Secondary Constructor in Kotlin:
Code :
fun main(args: Array<String>) {
employeeID(2040050223, “Java”)
employeeID(2040050228,”Kotlin”,1500000.9)
}
class employeeID {
constructor (NEWemp_id :Int, NEWemp_name: String ) {
var id: Int = NEWemp_id
var name: String = NEWemp_name
print(“The Employee id is: $id, “)
println(“Name of the Employee: $name”)
println()
}
constructor (NEWemp_id :Int, NEWemp_name: String ,NEWemp_salary : Double) {
var id: Int = NEWemp_id
var name: String = NEWemp_name
varsalary : Double = NEWemp_salary
print(“The Employee id is: $id, “)
print(“Name of the Employee: $name, “)
println(“The salary also of the Employee: $salary”)
}
}
Explanation: The above program also uses two employee IDs and constructors to get the details like employee name, employee id, and salary of one of the employees.
Code:
//main function – This defines the main function
fun main(args: Array<String>)
{
Add(60,90)
}
class Add {
// calling another secondary using this
constructor(a:Int, b:Int) : this(a,b,85) {
varsumoftwo = a + b
println(“The sum of the above two number 60 and 90 is: $sumoftwo “)
}
// this executes first
constructor(a:Int, b:Int, c:Int) {
varsumofthree= a + b + c
println(“The sum of three numbers 60,90 and 85 is: $sumofthree “)
}
}
Explanation: To above program explains the use of constructor inside the constructor, here we have two constructors which are typing the value of the addition of two numbers in the first constructor and the other is giving the value of three numbers in the second constructor. The above program also explains that initialization happens separately in Kotlin constructor where the values initialized can be reused in another constructor just by calling the function.
In the above article, we discussed and also learned about Kotlin Constructor and various ways of creating constructors and different uses of the primary and secondary constructors. You can also use a constructor in different ways according to your use as the main code is write inside the constructor and the values are initialize from later. We also learned that the primary constructor uses in it block to carry the execution where the initialization of variables and values takes place, while in the case of a secondary constructor, then you have to call Primary Constructor in a different form.
We hope you like our post learn more at mcp
MCP is the right place for best computer Courses institute and advance Courses in Mohali and Chandigarh.The Complete Programming Academy can change your life – providing you with the knowledge, skills, and performance in a second language which helps you to excel in your job.You can also Contact us for 6 month industrial training institute in Mohali.