Class in Kotlin

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

Classes in kotlin uses 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

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

In order to create an object/instance to the 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 default and this constructor is known as default constructor

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

Default constructor will be created only in case of when 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 compiles 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 parameterized constructor, 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, primary constructor may or may not accept parameters.

Primary constructors accepts 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 primary constructor :

Unlike functions, you can provide the parameter type in 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 default value for the parameters in the constructor, we can provide default value for the constructor using assignment operator in kotlin .

Default value will be ignored if user passes 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 same number of parameters with same data type.

Below example throws error as primary and secondary has 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.memberVariable
        println("Bulb color is  : $color")
    }
}
fun main(args: Array<String>) {
    var someObject = Bulb("Orange")
    someObject.memberFunctionExample()
    // calling primary constructor
    var someObjectWithPrimary = Bulb("karthiq")
}

Error:(1, 12) Kotlin: Conflicting overloads: public constructor Bulb(color: String) defined in Bulb, public constructor Bulb(name: String) defined in Bulb

Vararg in functions

Inner & Nested Classes in Kotlin

In kotlin, you can create/declare a class inside another class, these class are only accessible in the outside class with reference of Outer class then by inner class

This kind of inside class can be categorized into two types.

  • Nested Class
  • Inner Class
  • Anonymous Inner Class

Nested Class :

Inner classes are present inside a class, with normal class declaration. Nested class cannot access the properties of the outer class.

You can provide access levels to the nested classes in kotlin, by default the access level is public, which mean any class can access the inner class by creating object.

Nested classes are most often used to associate two related classes together where one class would have very little meaning or no meaning without its outer class

For example, consider below Nested class example:


class OuterClass{
	var outvariable = 98;
    class InnerClass{
        fun innerClassFunction(){
            println("I am a print statement")
        }
    }
}
fun main(args: Array<String>) {
    OuterClass.InnerClass().innerClassFunction();
    // you use after saving inner class object in variable
    var oi = OuterClass.InnerClass()
    oi.innerClassFunction()
}

In above class if we try to access the outer class variable OutVariable in inside the Nested class we may face error like, below example demonstrate it


class OuterClass{
    var outvariable = 98;
    class InnerClass{
        fun innerClassFunction(){
            // Acceesing Outer Class value
            println(outvariable)
        }
    }
}
fun main(args: Array<String>) {
    var oi = OuterClass.InnerClass()
    oi.innerClassFunction()
}

Inner Class in Kotlin :

Inner class is nothing but modified Nested class with access to the outer class members like variable and functions. Inner class will carry a reference to the Outer class, so we have to create an object for outer class to access the inner . Inner class are declared with inner keyword in kotlin

Attempting to create an inner class object without the outer class object results in a compiler error.


class OuterClass{
    var outvariable = 98;
    inner class InnerClass{
        fun innerClassFunction(){
            // Acceesing Outer Class value
            println(outvariable)
        }
    }
}
fun main(args: Array<String>) {
    // see the difference below, as we are creating object to outer class here
    var oi = OuterClass().InnerClass()
    oi.innerClassFunction()
}

Same name Variable/Functions Inner Class in Kotlin (this@):

Sometimes, you might have same name for your variable/functions in your inner and outer class, In such cases we would be using this@ keyword to specify from which class you want to access the variable/functions.


class OuterClass{
    var someVariable = 98;
    inner class InnerClass{
        var someVariable = 14;
        fun innerClassFunction(){
            // Accessing Outer Class value
            println("outer class variable : "+this@OuterClass.someVariable)
            println("inner class variable : "+this@InnerClass.someVariable)
        }
    }
}
fun main(args: Array<String>) {
    // see the difference below, as we are creating object to outer class here
    var oi = OuterClass().InnerClass()
    oi.innerClassFunction()
}

If you are like, then you might have question that what if I do not mention from which class you want to access, Kotlin refers the inner class first hen it might check in outer class.

So by default kotlin checks in inner class for the variables and functions before referring the outer class.


class OuterClass{
    var someVariable = 98;
    inner class InnerClass{
        var someVariable = 14;
        fun innerClassFunction(){
            // Accessing same name variable without @this
            println(someVariable)
        }
    }
}
fun main(args: Array<String>) {
    // see the difference below, as we are creating object to outer class here
    var oi = OuterClass().InnerClass()
    oi.innerClassFunction()
}

Anonymous Inner Classes :

Anonymous inner class instances are created using an object expression:


window.addMouseListener(object: MouseAdapter() {
    override fun mouseClicked(e: MouseEvent) {
        // ...
    }
                                                                                                            
    override fun mouseEntered(e: MouseEvent) {
        // ...
    }
})

Anonymous Inner Classes with lambda :

If the object is an instance of a functional Java interface (i.e. a Java interface with a single abstract method), you can create it using a lambda expression prefixed with the type of the interface:


val listener = ActionListener { println("clicked") }

Parameters with lambda

aaaaaaaaaaaaa
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions

Recent Addition

new tutorial Selenium Online Training : Our next online training course for Selenium with Java starts from 17th December 2018.

You can attend first 3 classes for free, the total course fee is INR 10,000

The course time would be 8.00 PM(IST) for the first three classes

If you are interested to learn, then you can join the course by sending email to chercher.tech@gmail.com

or Register below


 
Join My Facebook Group
Join Group