A class is a blue print defined which groups functions and properties. Classes in Kotlin are defined using the keyword class followed by the class name. The body goes inside the curly braces.
Syntax of class in Kotlin
An instance of the class is instantiated in the following way
instance of the class
Contrary to Java, new isn’t a keyword in Kotlin.
new is not a keyword
Classes by default are final in Kotlin. To make a class non-final we need to append the keyword open.
Syntax of class in Kotlin
By default classes in Kotlin are not inheritable. The open annotation allows others to inherit from this class.
Let’s create a class with a few functions and a property.
Example of class in Kotlin
Suppose that the function main belongs to the Test.kt class. To access members and functions, we need to use the dot operator.
Init
Init
The code inside the init block is the first to be executed when the class is instantiated. The init block is run every time the class is instantiated, with any kind of constructor as we shall see next.
Second initializer block
We can write multiple init blocks also. In this case the blocks will sequentially executed.
Constructor
Kotlin constructors are special member functions that are used to initialize properties. By default a class has an empty constructor. In the previous examples we had empty contructurs.
Primary Constructors
Primary Constructors in Kotlin are defined in the class header itself.
Primary constructors
The primary constructors definition goes inside the class header. We have defined the property types(val/var) in the constructor itself. Note: Unless stated as a var, by default, constructor arguments are val.
Constructor Default Values
Kotlin allows us to specify default values in the constructor itself.
Output
Author Peter writes at Inspire Coding
Author David writes at uigitdev
Secondary Constructors
Secondary Constructors are written inside the body of the class by prefixing with the keyword constructor. The most common usage of secondary constructors comes in subclasses when you need to initialize the class in different ways.
Output
Name is Peter and Age is 31
If the functions (here the consturctor) contains arguments with the same name, then must refer to the primary variable using the this keyword. init block is used to initialise the member property skill. The secondary constructor delegates to the primary constructor using: this.
Output
Name is Peter and Age is 31
Name is Peter and Age is 31 Skill is Kotlin
Questions
I hope the description was understandable and clear. But if you have still questions, then leave me comments below! 😉
Have a nice a day! 🙂