Table of content

Class in Kotlin

Class is a blueprint for an object in kotlin, where the definition of the object resides.

Classes in kotlin use class keyword to specify them, we specify the characteristics of the object using properties/variables and we specify behaviors using functions.

Classes helps you to create your own type by combining functions and variable in the class.

In below example, color, isOn are variables/properties and switchOn(), SwitchOff() are functions/behaviors of the class.

class Bulb {
    // variables (data member)
    var color: String = "BLUE"
    private var isOn: Boolean = false
    // member function
    fun switchOn() {
        isOn = true
    }
    // member function
    fun switchOff() {
        isOn = false
    }
}

A class can contain below items in it:

  • Constructors
  • Functions
  • Variables
  • Nested classes
  • Inner Classes
  • Object declarations
  • lambdas

The class contains all the above items within the curly braces { }, we can access all the items by creating an object/instance to the class.

To create an object/instance to the class, you have to call the constructor of the class.

Functions in Kotlin

Constructors

A constructor is a special type of functions in a class, which is automatically called when the object of that class is created or when you call constructor, it automatically creates the object.

Constructor types based on Parameters :

  • Default Constructors
  • No-Param Constructors
  • Parameterized Constructors

Constructor types based on Declaration :

  • Primary Constructor
  • Secondary Constructors

Default Constructors

It is must, that every class in kotlin should have at least one constructor, but it not mandatory for the user to write the constructor.

So, when you don't write any constructor for the class, the kotlin compiler will write a constructor by defaultand this constructor is known as default constructor

The Default constructor will not have any parameters, also you cannot write a default constructor.

The Default constructor will be created only in case when a user does not provide a constructor.

In below example, I have not created any constructor, so compiler will create a constructor
class Bulb {
    // variables (data member)
    var color: String = "BLUE"
    fun memberFnctionExample(){
        println("this class does not have any constructor");
    }
}

No-Param Constructors

No-param constructor is nothing but a constructor without any parameters, Once a constructor is present in the class then compiler will not create a constructor in kotlin.

While creating h object to the no-param constructor you don't have to pass any arguments.

class Bulb {
    // variables (data member)
    var color: String = "BLUE"
    fun memberFnctionExample(){
        println("this class does not have any constructor");
    }
    constructor(){
        println("example for no-param constructor")
    }
}
fun main(args: Array<String>) {
    var someObject = Bulb()
}

Parameterized Constructors

A constructor having parameters is called the parameterized constructor, a parameterized constructor can have any number of parameters and any type of parameters.

class Bulb {
    // variables (data member)
    var color: String = "BLUE"
    fun memberFnctionExample(){
        println("this class does not have any constructor");
    }
    constructor(name:String, age:Int){
        println("Name received is : $name")
        println("age received is : $age")
    }
}
fun main(args: Array<String>) {
    var someObject = Bulb("chercher tech", 1)
}

Kotlin's Primary Constructor

Primary constructors are defined in the header of the class in kotlin, the primary constructor may or may not accept parameters.

Primary constructors accept a list of comma-separated parameters with their type modifiers. These parameters are used to initialize the member variables of the class.

class Bulb constructor(name:String, website:String){
    // variables (data member)
    var color: String = "BLUE"
    fun memberFunctionExample(){
        println("Name Value is : $name")
        println("Website Value is : $website")
    }
}
fun main(args: Array<String>) {
    var someObject = Bulb("chercher tech", "https://cherhcer.tech")
	someObject.memberFunctionExample()
}

Init Block in kotlin

If you notice the primary constructor, there is no place in the header to include some lines code for the primary constructor, except for the declaration of type variables.

To overcome this kotlin provides an initialization block called init block. You should not use the init block other than initialization of variables in kotlin class.

is run for all the constructors irrespective of primary and secondary without any call to init block.

class Bulb constructor(ColorOfBulb:String){
    // variables (data member)
    var color: String
    fun memberFunctionExample(){
        println("this is just member function example");
    }
    init{
		this.color = ColorOfBulb
    }
}
fun main(args: Array<String>) {
    var someObject = Bulb("GREEN")
}

It is not mandatory to have initializer block in kotlin class, you can initialize the variable without init block. Just write the variable in class as first statements

class Bulb constructor(ColorOfBulb:String){
    // variables (data member)
    var color: String = ColorOfBulb
    fun memberFunctionExample(){
        println("The color of the bulb is : $color");
    }
}
fun main(args: Array<String>) {
    var someObject = Bulb("GREEN")
	someObject.memberFunctionExample()
}

val and var in the primary constructor :

Unlike functions, you can provide the parameter type in the constructor by using val and var. we can change the value of the var parameters but we cannot do changes for val parameters.

If we want to change the value of the parameters then we should change the value inside a member function or inside the init block, but not outside of the functions.

You can only re-assign value for var variable not for val variables.

class Bulb constructor(var ColorOfBulb:String, val size:String){
    fun memberFunctionExample(){
        // example for changing the constructor parameter values in kotlin
        ColorOfBulb = "WHo Cares"
        println("The color of the bulb is : $ColorOfBulb");
    }
}
fun main(args: Array<String>) {
    var someObject = Bulb("GREEN", "Small")
	someObject.memberFunctionExample()
}

Default Values in the Primary Constructor :

Sometimes to reduce the overburden we may need to have a default value for the parameters in the constructor, we can provide a default value for the constructor using assignment operator in kotlin.

The Default value will be ignored if the user passes a value for the parameter.

class Bulb constructor(var ColorOfBulb:String = "Neon", val size:String = "Large"){
    fun memberFunctionExample(){
        // example for default values for constructor parameter
        println("The color of the bulb is : $ColorOfBulb");
        println("The size of the bulb is : $size")
    }
}
fun main(args: Array<String>) {
    var someObject = Bulb("Orange")
    someObject.memberFunctionExample()
}

Secondary Constructors

Secondary Constructors are written inside the body of the class with the keyword constructor.

class Bulb{
    fun memberFunctionExample(){
        // example for default values for constructor parameter
        println("Example for secondary constructor");
    }
    constructor(color:String){
        println("Bulb color is  : $color")
    }
}
fun main(args: Array<String>) {
    var someObject = Bulb("Orange")
    someObject.memberFunctionExample()
}

Combination of Primary & Secondary Constructors

If the class has a primary constructor, each secondary constructor needs to delegate to the primary constructor, either directly or indirectly through another secondary constructor(s).

Delegation to another constructor of the same class is done using the this keyword

class Bulb constructor(value1:Int, value2:Int){
    init {
        println(value1 * value2)
    }
    var memberVariable ="zzzz"
    fun memberFunctionExample(){
        // example for default values for constructor parameter
        println("Example for secondary constructor");
    }
    constructor(color:String):this(10, 20){
        this.memberVariable
        println("Bulb color is  : $color")
    }
}
fun main(args: Array<String>) {
    var someObject = Bulb("Orange")
    someObject.memberFunctionExample()
    // calling primary constructor
    var someObjectWithPrimary = Bulb(3, 4)
}
You cannot have primary more than one constructor with the same number of parameters with the same data type.

Below example throws an error as primary and secondary has the same number of parameters and same dataTypes.
class Bulb constructor(name:String){
    init {
        println("the name is  : $name")
    }
    var memberVariable ="zzzz"
    fun memberFunctionExample(){
        // example for default values for constructor parameter
        println("Example for secondary constructor");
    }
    constructor(color:String):this(10, 20){
        this&
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions