You are here
Home > Kotlin

Referential equality and Structural equality

Referential equality and Structural equality

Referential equality and Structural equality

In this post of kotlin we will discuss Referential equality and Structural equality, packages, imports, kotlin is operator.

Referential equality and Structural equality

  • When we work will object-oriented programming, there are two types of quality comes one is referential equality and structural equality.
  • Referential equality comes when two separate references point to the exact same instance in memory.
  • Structural equality comes when two objects are separate in memory but they have same value.
  • For referential equality == (double equality operator) is use.
  • For Structural equality === (triple equality operator) is use.

Example:
class Students
{

}
fun main(args:Array<String>)
{
var a:Int=10;
var b:Int=10;
var s1=Students();
var s2=Students();
//structural equal
if(a==b)
{
println(“a and b are structural equal”);
}
else
{
println(“a and b are not structural equal”);
}
//referential equal
if(s1===s2)
{
println(“s1 and s2 are referential equal”);
}
else
{
println(“s1 and s2 are not referential equal”);
}
}
output:

is Operator

  • For checking whether a given object is a type of specific class or not at runtime we use is

Example:
class Exam
{

}
fun main(args:Array<String>)
{
var e=Exam();
var obj:String=”Kotlin”;
if(obj is String)
{
println(“length of obj=”+obj.length);
}

if(obj !is String )
{
println(“obj is a string”);
}
else
{
println(“obj is not string”);
}

if(e is Exam)
{
println(“e is object of type Exam”);
}
}
output:

Explanation:
Here we create object of string class and we check whether it is an object of String class and if yes we get the length of it. We create a class Exam and create object of class Exam and check it whether it is object of Exam class or not.

Packages

  • for creating package in kotlin we use package keyword and its name.
  • Ex:

Package com.example;

  • Packages is use to split code into different namespace.

Imports

  • For including created packages or in-built packages into class, objects or interfaces use import keyword.
  • If we have to include multiple classes from the same package use * for including all classes.
  • Ex:

Import com.example;
Import com.*;
Keep Visiting TechwithR.com for more upcoming top technical articles and also see my new blog Mag4info. and for kotlin tutorial also see my blog kotlin category.

You can also by SQL 70-761 book write by me from Amazon.
You can also by Kotlin Book write by me from Amazon.

Leave a Reply

Top