Monday, 18 December 2017

Kotlin: classes and objects

Objects and class in Real World scenario

Object
An Object is a real-world entity. For example, book, cat, box, bus, keyboard, person, screen, cell phone etc., all are objects.

How can we differentiate objects
1. Depend on their properties
2. Depend on their behaviors

Differentiating two objects based on their properties
Let’s say, there are two persons A and B.

First let’s try to find what are the possible properties for the person object

Possible properties for a person
height, weight, color, Education Qualification, country, address are all come under person properties.

Now by comparing these properties we can easily differentiate two persons.
Properties
Person A
Person B
Height
6ft
5.5ft
Weight
75Kg
60Kg
Color
White
Black
Country
India
America

As shown in the above table, both the persons has their own properties, So we can differentiate based on them.

Differentiating two objects based on their behavior
consider the same two persons A and B. will try to figure out possible behaviors for the person object

Possible behaviors are
walk, run, swim, eat, sleep, see, hear etc., Now by comparing these behaviors we can easily differentiate two persons.

Behavior
Person A
Person B
Walk
10km/hr
12km/hr
run
20km/hr
18km/hr
sleep
8 Hrs/day
6Hrs/day
Behavior
Person A
Person B

Class
In normal terms I call class as a category.

All persons come under Human category
cat, lion, Elephant come under Animals Category

So a class or category is a group of objects with similar properties and behaviors.

Objects and class in Programming Terminology

What Is an Object?
An object is a software bundle of related state and behavior. The main advantage of Kotlin is you can compare objects in Kotlin with real world objects. So it is very easy to work with objects in Kotlin.

What Is a Class?
A class is a blueprint or prototype from which objects are created.

You can define a class using 'class' keyword.

Syntax
class ClassName{
 // Properties
 // Functions
}

Example

class Employee {
 var firstName : String = ""
 var lastName : String = ""
}

Above snippet define 'Employee' class, it has two properties (firstName, lastName) defined.

How to define object to the class Employee?
var emp1 = Employee()
Above statement is used to define an object to the class Employee.

How to access the properties associated with object emp1?
Members of the object (firstName and lastName) are accessed using ‘.’ Notation.

Syntax
objName.propertyName

Example
emp1.firstName = "Chamu"
emp1.lastName = "Gurram"


Employee.kt
class Employee {
 var firstName: String = ""
 var lastName: String = ""
}


Main.kt

fun main(args: Array<String>) {

 var emp1 = Employee()
 emp1.firstName = "Chamu"
 emp1.lastName = "Gurram"

 println("First name : ${emp1.firstName}")
 println("Last name : ${emp1.lastName}")
}


Output

First name : Chamu
Last name : Gurram







Previous                                                 Next                                                 Home

Saturday, 16 December 2017

Kotlin: continue statement

continue statement skips the current iteration of loops(Ex: for, while, do-while loops). Just like break, continue also has two forms.
    1. unlabelled continue
    2. labelled continue

Unlabelled continue
    Syntax
        continue;

ContinueDemo.kt
fun main(args: Array<String>) {

 for (i in 1..10) {
  if (i % 2 != 0) {
   continue
  }
  print("$i ")
 }
}

Output
2 4 6 8 10

UnlabelledContinueInnerLoop.kt
fun main(args: Array<String>) {

 for (i in 1..5) {
  for(j in 1..10){
   if(j % 2 != 0){
    continue
   }
   print("$j ")
  }
  println()
 }
}

Output
2 4 6 8 10 
2 4 6 8 10 
2 4 6 8 10 
2 4 6 8 10 
2 4 6 8 10

Labelled Continue
Kotlin allows us to label any expression.

How to create a label?
Define an identifier followed by @ sign.

Ex:
outerLoop@, processState@

we can use continue statement with labels.

Syntax
continue@labelIdentifier

Ex
continue @outerLoop
continue @processState


ContinueLabelledDemo.kt
fun main(args: Array<String>) {

 outerLoop@ for (i in 1..5) {
  for (j in 1..10) {
   if (j > 5) {
    println()
    continue@outerLoop
   }
   print("$i ")
  }
 }
}


Output
1 1 1 1 1 
2 2 2 2 2 
3 3 3 3 3 
4 4 4 4 4 
5 5 5 5 5





Previous                                                 Next                                                 Home

Friday, 15 December 2017

Kotlin: break statement

'break' statement is used to come out of the loop. 'break' statement can be used in two forms.
         a. unlabeled break
         b. labeled break

unlabeled break
Unlabeled break is used to come out from nearest closing loop.

Syntax
break

BreakDemo.kt
fun main(args: Array<String>) {

 for (i in 1..10) {
  println(i)

  if (i == 5) {
   break
  }
 }
}

Output
1
2
3
4
5

BreakDemoInnerLoop.kt
fun main(args: Array<String>) {

 for (i in 1..5) {
  for (j in 1..i) {
   print("$j")
  }
  println()
 }
}

Output
1
12
123
1234
12345

Labelled break
Kotlin allows us to label any expression.

How to create a label?
Define an identifier followed by @ sign.

Ex:
outerLoop@, processState@

By specifying the label, we can come out of the label.

Syntax
break@labelIdentifier

Ex
break@outerLoop
break@processState


LabelledBreakDemo.kt
fun main(args: Array<String>) {

 var counter: Int = 0;

 outerLoop@ for (i in 1..5) {
  for (j in 1..i) {
   counter++
   print("$j")

   if (counter == 6) {
    println("\nBreaking out of the outer loop")
    break@outerLoop
   }
  }
  println()
 }
}


Output
1
12
123
Breaking out of the outer loop




Previous                                                 Next                                                 Home

Kotlin: while, do-while loops

while loop
while statement executes a block of statements until a particular condition is true

Syntax
while (expression) {
      //statements
}

The expression in the while statement must evaluates to a boolean value, otherwise compiler will throw error. While statement first evaluates the expression, until the expression evaluates to true, it executes the code inside the while block, otherwise it comes out of the while loop.

Example: Print numbers from 0 to 9 using while loop.

WhileDemo.kt
fun main(args: Array<String>) {

 var counter : Int = 0
 
 while(counter < 10){
  println(counter)
  counter++
 }
}

Output
0
1
2
3
4
5
6
7
8
9


do-while loop
do-while is also a loop construct like while, but evaluates its expression at the bottom of the loop instead of the top.

    Syntax
    do {
        //statement(s)
    } while (expression)


DoWhileDemo.kt
fun main(args: Array<String>) {

 var counter : Int = 0
 
 do{
  println(counter)
  counter++
 }while(counter < 10)
}


Output
0
1
2
3
4
5
6
7
8
9

What is the difference between while and do-while ?
Statements within the do block are always execute at least once even if the expression evaluates to false.



Previous                                                 Next                                                 Home

Kotlin: for loop

‘for’ loop is used to iterate over a collection, array, ranges etc.,

By using ‘for’ loop, you can iterate over anything that provides iterator.

Looping through arrays
Syntax
for(ele in array){

}

ArrayDemo.kt
fun main(args: Array<String>) {

 var arr: Array<Int> = arrayOf(2, 3, 5, 7)

 for(ele in arr){
  println(ele)
 }
}

Output
2
3
5
7

Loop over a range
ArrayDemo.kt
fun main(args: Array<String>) {

 for(ele in 1..10){
  println(ele)
 }
}

Output
1
2
3
4
5
6
7
8
9
10

Loop over a string
ArrayDemo.kt

fun main(args: Array<String>) {

 var message = "Good Morning"
 
 for(c in message){
  print(c)
 }
}

Output

Good Morning



Previous                                                 Next                                                 Home

Kotlin: Use When as expression

You can use 'when' as expression. If you use 'when' as expression, the value of the matched branch will be the value of 'when' expression.

WhenDemo.kt
fun main(args: Array<String>) {
 var a : Int = 2
 var s : String = "cube"
 
 var result = when {
  s.equals("double") -> a * a
  s.equals("cube") -> a * a * a
  else -> a
 }
 
 println("result is $result")

}

Output

result is 8


Previous                                                 Next                                                 Home

Thursday, 14 December 2017

Kotlin: Using when as if-else if ladder

You can also use ‘when’ expression as if-elseif ladder. If you do not specify any argument to when expression, it can be used as if-else if ladder.

ConditionDemo.kt
fun main(args: Array<String>) {
 var marks: Int = 65

 if (marks < 35)
  println("You are failed");
 else if (marks < 50)
  println("You are passed and got third class");
 else if (marks < 60)
  println("You are passed and got second class");
 else if (marks < 70)
  println("You are passed and got first class");
 else
  println("You are passed and got distinction");
}


Output
You are passed and got first class

You can implement above if-else if-else logic using when expression like below.

WhenDemo.kt

fun main(args: Array<String>) {
 var marks: Int = 65

 when {
  (marks < 35) -> println("You are failed")
  (marks < 50) -> println("You are passed and got third class")
  (marks < 60) -> println("You are passed and got second class")
  (marks < 70) -> println("You are passed and got first class")
  else -> println("You are passed and got distinction")
 }

}

Output
You are passed and got first class



Previous                                                 Next                                                 Home