InterviewSolution
| 1. |
What are the different types of constructors available in Kotlin? Explain them with proper examples. |
|
Answer» <P>There are two types of Kotlin constructors:
If no annotations or ACCESS modifiers are provided, the constructor keyword can be omitted. The initialization code can be placed in a separate initializer block prefixed with the init keyword because the primary constructor cannot contain any code. For example, // KOTLINfun main(args: Array<String>) { val s1 = Sample(1, 2)}class Sample(a : Int , b: Int) { val p: Int var q: Int // initializer block init { p = a q = b println("The first parameter value is : $p") println("The second parameter value is : $q") }}Output:- The first parameter value is: 1The second parameter value is: 2Explanation - The values 1 and 2 are SUPPLIED to the constructor arguments a and b when the object s1 is created for the class Sample. In the class p and q, two attributes are specified. The initializer block is called when an object is created, and it not only sets up the attributes but also PRINTS them to the standard output.
Output:- The first parameter value is: 1The second parameter value is: 2The compiler determines which secondary constructor will be called based on the inputs provided. We don't specify which constructor to use in the above program, so the compiler chooses for us. In Kotlin, a class can contain one or more secondary constructors and at most one primary constructor. The primary constructor INITIALIZES the class, while the secondary constructor initialises the class and adds some additional logic. |
|