WEB Button DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

Kotlin - Constructors

In this chapter we will learn the basics of constructors in Kotlin

Kotlin has two types of constructor: primary constructor and secondary constructor

Kotlin the primary constructor initializes the class

class Person(val firstName: String, var age: Int) {
   // class body
}
In the above example, we have declared the primary constructor inside the parenthesis first name is read-only as it is declared as “val”, while the field age can be edited. In the following example, we will use the primary constructor
fun main(args: Array) {
   val person1 = Person("welookups.com", 18)
   println("First Name = ${person1.firstName}")
   println("Age = ${person1.age}")
}
class Person(val firstName: String, var age: Int) {
}


The above piece of code will automatically initialize the two variables and provide the following output in the browser.
First Name = welookups.com
Age = 18

Other example secondary constructor and are using the above example to implement the same.
fun main(args: Array) {
   val HUman = HUman("welookups.com", 18)
   print("${HUman.message}"+"${HUman.firstName}"+
      "Welcome to the example of Secondary  constructor, Your Age is-${HUman.age}")
}
class HUman(val firstName: String, var age: Int) {
   val message:String  = "Oh!!!"
	constructor(name : String , age :Int ,message :String):this(name,age) {
   }
}



Output
Oh!!! welookups.comWelcome to the example of Secondary  constructor, Your Age is- 18