Category Archives: Kotlin Tutorial

Kotlin Tutorial

Kotlin Operator Overloading

Kotlin Operator Overloading

Kotlin allows us to provide implementation for predefined set of operators on our types. These operators have fixed procedure and fixed symbolic representation, like + or *. When you will use operator in kotlin so it’s corresponding member function is called.

Let’s see some operations.

Unary Operations:

Expression Translated to
+a a.unaryPlus()
-a a.unaryMinus()
!a a.not()

Increment and Decrement Operations:

Expression Translated to
a++ a.inc()
a– a.dec()

Binary Operations:

Expression Translated to
a+b a.plus(b)
a-b a.minus(b)
a*b a.times(b)
a/b a.div(b)
a%b a.rem(b), a.mod(b) (deprecated)
a..b a.rangeTo(b)

Example: Overloading + Operator: See below example which is using for plus operator.

Output: The output of this code will be like below image.

op-over-1

In above example you can see that plus() is declared with operator keyword which will tell to complier that + operator will be overloaded. According to Above tables Expression point1+point2 will translated to point1.plus(point2).

 

Example: –Operator Overloading: –operator means decrement under the hood. In this example we will explain overloading of — operator. According to table suppose The expression is –a so it will translated to a.dec() for compiler and will tell that this operator is overloading.

 

Below line

is equivalent to

See below code.

Output: The output of above code will be.

op-over-2

Kotlin Extension Function

Kotlin Extension Function

In Kotlin We can use extension function to extend class. In Most of the programming langauge we have to create derived class to do this. The Extension Function is declared outside the class and is a member function of class.

Example: Let’s get understand it by an example, In below example we are going to remove first two word from string. Check below code

In aboce code removeFirstTwoChar() is an extension function which is added to the String class.
String class is receiver type and the this keyword inside the extension function is receiver object.

 

Output: So here is the output.

ext-fun-1

 

Kotlin Companion Objects

Kotlin Companion Objects

In kotlin we can call method using class name, for that we need to create a companion object through object declaration with companion keyword.

Let’s understand it by example, we will create two example, in first one we will call method without Companion Object and in second example we will use Companion Object.

Example:Without Companion Object: In this example we are not using Companion Object.

Output: The output of this code will be like below image.

Campnion!

Example: With Companion Object: In this example we will use campanion object. You can see in below example that we used object declaration with companion keyword for Test object.

It is not compulsary to use Object Name (i.e. Test in above example), It is optional and can be omitted. Check below code.

Output: It will be same like above image, still you can see below image.

Campnion2

Kotlin Object Declaration

Kotlin Object Declaration

In this article we are going to learn about Object Declaration(Singletons) & Object Expression .

Object Declaration: A class which have only one instance and follow object-oriented pattern called Singleton.

For an example suppose we are using SQL Database in our application as backend , You have created a class for database connection which you want to reuse same connection. For this you can create singletion class so that you can use same connection for every client.

For singleton class creation kotlin provide us object declaration feature, object keyword is used for this.

Syntax :-

In above code we can see that it combines Singleton class declaration and object declaration(single instance) of SingletonDemo classs.

Example: Let’s get understand this by an example. See below code and output.

Output:

obj-d-1

Kotlin Object Expression

We can also use this object keyword to create objects of an anonymous class which is known as anonymous objects.Sometimes we need to create an object of a slight modification of some class, without explicitly declaring a new subclass for it, so here Kotlin provides us this concept with object expressions and object declarations.

You can see in below code that the an anonymous object is declared which extending MousAdapter class. There are two overrides methods mouseClicked() and mouseEntered() of MouseAdapter class. You can also assign a name of anonymous object and store it in a variable. Through below code .

Example: Let’s understand it by an example, In this example we have stored anonymous object in variable, The variable name is w3adda which extends ExpressionDemo class and override learn() method.

Output: Let’s run this code you will get output like below image.

obj-d-2

Example with class constructor: Let’s make one more example in which class has constructor and extended by anonymous object. See below code

Output: output of this code will look like below image.

obj-d-3

Kotlin Sealed Class

Kotlin Sealed Class

The class which is declared with “sealed” modifier before the name of class known as sealed class. Sealed classes are used to represent restricted class hierarchies. A sealed class can have subclasses but all of them need to declare in the same file as the sealed class itself. In Kotlin sealed class we don’t need to use “else” statement.

Example: Let’s get understand it by an example, see below code.

Here, SealedDemo is a “sealed” class, which has two types: OPT1 & OPT2.
In the main class have created an object and assigned at run time.
Here we have applied “when” clause so that we can implement the final output at runtime.

Output: The output of this code will look like below image.

sealed-1

Kotlin Data Class

Kotlin Data Class

The class which is declared as “data” known as data class. All data classes must have at least one primary constructor and primary constructor should have at least one parameter. It can not be open, abstract, inner and sealed. Data class can extend other classes also can implement interface. It have some inbuilt function like “toString()” ,”hashCode(),equals() ,copy() etc. and we can use them.

Example: Let’s get understand it by an example. See below code.

Here, I have used some inbuilt function which are created by the compiler, when we declared class as “data” class. Let’s understand inbuilt function one by one

toString(): This function is used to returns a string representation of the object. Check below code which is used in above example.

hashCode(): This function is used to returns hash code of the object. Check below lines which is used in above example for printing hashCode of object.

Copy(): This function is used to create a copy of an object with some of its properties and also can copy whole object. Check below lines.

Equals(): This function is used to check whether objects are equals. Check below lines.

Output: Let’s run this code you will get output like below image.

dataclass-1

 

Kotlin Nested Class

Kotlin Nested Class

Nested Class: Nested class is a class which is declared inside the class or interface. In Kotlin, nested class is by default static, hence it can be accessed without creating any object of that class.

Syntax:

Example: You have to use . notataion for using nested class and its member with its enclosing class. Here Outer Class is an enclosing class of Nested Class. Let’s see below example.

Output: So when you simply run this code this will give output like below image.

nested-1

Kotlin Inner Class: Through kotlin nested class we can not access to outer class instance, to solve this issue we need to change nested class to inner class, Nested class has the capabilties to access outer class members.

Example: In below example we have change nested class to inner class.

Output: The output of this class will look like below image.

nested-2

Kotlin Interfaces

Kotlin Interfaces

The Kotlin Interface can contain method implementation and also abstract methods declaration, It is similar to Java 8.To use interface’s defined functionality we can implement it by a class. We can define interface in kotlin by keyword “interface”.

Define interface in Kotlin: As I told you that keyword “interface” is used to define interface in kotlin, See below code.

In above code “DemoInterface” an Interface, “demoVar” is an abstract property . infAbs () is an abstract method. The above interface also has a non-abstract method that is welcome().

 

Implementation of Interface: Let’s get understand that how we can implement interface by a class with the help of below simple code.

In above code DemoImp is a class which implements DemoInterface interface. The DemoImp class overrides abstract member demoVar and abstract method infAbs().

Example: Now let’s get know more about interface by it’s example, check below code.

Output: The output of this code will look like below image.

interface-1

Multiple Inheritance in Kotlin: Kotlin does not provide multiple inheritance but we can allow it using interface, we can implement one or more interface in single class. See below example.

Example:

Output: So output of this code will look like below image.

interface-2

Issue : Now suppose we have two interface with same non-abstract method name, suppose it is printMe() method. Now see what will happen. Check below code.

Output: It will give us error .

Solution : You can simply solve this problem by using below code.

Output: Now you can see in below image the output of above code.There is no error occurred.

interface-3

Kotlin Abstract Class

Kotlin Abstract Class

An abstract class is class which can not be instantiate it means you can not create an object of abstract class.However we can inherit them from subclass.

The members of an abstract class are non-abstract if you don’t declare or explicitly use abstract keyword to make them abstract.

Example :-

Here , Employee is an abstract class which object can not be created.

Salary is non-abstract property and displaySal is non-abstract method. If you want to override these members so you need to declare them “open”.

displayJob is abstract method. This function must be overridden in subclass,it doesn’t have any implementation

We don’t need to declare abstract class as “open” because abstract classes are always open.

Example: Let’s get understand Kotlin Abstraction by below example. Check below code.

Output: The output of above code will look like below image.

kotlin-abstract

Kotlin Visibility Modifiers

Kotlin Visibility Modifiers

Visibility Modifiers: Kotlin provides a number of Visibility Modifiers that can be used in classes, objects, properties, member function etc. In Above example I have used private visibility modifiers for isActive Property , it means it can use only within the class.

There are four visibility modifiers that are:

1.private: This modifiers can access or visible only inside the class.

2.public: This modifiers can access or visible everywhere.

3.protected: This modifiers can access or visible to the class and its subclass.

4.internal: It is accessble inside the module.

Kotlin Inheritance

Kotlin Inheritance

Inheritance is mechanism in which child class aquires all the properties and behaviors of parent class.It represent IS-A relationship. Inheritance is used to achieve Method Overriding and Code Reusability.

Syntax of Inheritance in Kotlin:

Example: In below example we have created two class one is Parentclass and ChildClass. We will use Parentclass function in child class.

ParentClass.kt : Here created welcome function and define class as open so that we can use it in child class.

ChildClass.kt: Here we have extend ParentClass so that we can use it in this class.

Output: Output of this code will look like below image, It prints the ParentClass.kt’s welcome function which is called by our child class.

inheritance-1

Kotlin Getters and Setters

Kotlin Getters and Setters (Bean)

Beans are classes that encapsulate many objects into a single object. It contains constructor, Getter, Setter Methods. With the help of Setter and Getter method user can set and get data. It also have zero argument constructor.

In Kotlin we do not need to write getter and setter method in model , getter and setter methods are auto genarated in Kotlin . It is very simple to create model in Kotlin support.

Example: Let’s get understand about Bean in Kotlin. Create a bean class.

Now Create a new Class like below Image.

get-set-1

Check below code.

How to instantitate Object of Bean class : From the below code you can instantiate object.

Setting Value: With the help of below syntax you can set value to bean.

Getting Value: With the help of below syntax you can get and print value from bean.

Output: Let’s run this code and you will get output like below image.

get-set-2