Wednesday, 31 May 2017

Control Statements in Kotlin

Control Statements in Kotlin :

1)If else does not have much difference.
2)For loop have a syntax change.
3)While and do while have minimal syntax change.


1)If else statement :


Java Code :

if(i>1){  
//code to be executed if condition1 is true  
}else if(i>2){  
//code to be executed if condition2 is true  
}  
else if(i>3){  
//code to be executed if condition3 is true  
}  
...  
else{  
//code to be executed if all the conditions are false  
}

Kotlin Code :

if (i > 1)
{
  //code to be executed if condition1 is true 
}
else if (i > 2)
{
  //code to be executed if condition2 is true 
}
else if (i > 3)
{
  //code to be executed if condition3 is true 
}
run({ 
  //code to be executed if all the conditions are false 
})

2)For Loop :

Java:

for(int i=1;i<=10;i++){  
        System.out.println(i);  
    }  

for(int i:arr){  
        System.out.println(i);  
    }  

Kotlin :

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

for (i in arr)
{
  System.out.println(i)
}

3)Switch Statement :

Java :

int number=20;  
    
switch(number){  
    case 10: System.out.println("10");break;  
    case 20: System.out.println("20");break;  
    case 30: System.out.println("30");break;  
    default:System.out.println("Not in 10, 20 or 30");  
    } 

Kotlin :

val number = 20
when (number) {
  10 -> println("10")
  20 -> println("20")
  30 -> println("30")
  else -> println("Not in 10, 20 or 30")
}

4)While Statement :

Java :


int i=1;
while(i<=10){
System.out.println(i);
i++;

Kotlin :


val i = 1
while (i <= 10)
{
println(i)
i++
}

4)Do While Statement :

Java :

int i=1;
do{
System.out.println(i);
i++;
}while(i<=10);
}  

Kotlin :

val i = 1
do
{
println(i)
i++
}
while (i <= 10)







No comments:

Post a Comment

Pojo class in kotlin