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)







Kotlin Add two numbers example

Java Add two numbers example :

Simple kotlin example of adding two numbers :

Java Code :

class Simple{
public static void main(String[] args){
int a=10;
int b=10;
int c=a+b;
System.out.println(c);
}}

Kotlin Code :

class Simple {
  @JvmStatic fun main(args:Array<String>) {
    val a = 10
    val b = 10
    val c = a + b
    println(c)
  }
}

Class and Objects in Kotlin

Classes and Objects in Kotlin
1)Class :
Classes in Kotlin are declared using the keyword class{: .keyword }:
class Address { }

The class declaration consists of :
·      Class name.
·      Class header.(optional)
·      Class body (surrounded by curly braces).(oprtional)

Both the header and the body are optional; if the class has no body, curly braces can be omitted.

class Address
2)Constructors :
Kotlin have two types of constructors.
1)Primary constructor : 
The primary constructor is part of the class header: it is used after the class name.
class Place constructor(firstName: String) { }
constructor keyword can be omitted if constructor does not have any annotations or visibility modifiers.
class Place(placeName: String) { }
Primary constructor cannot contain any code and Initialization code can be placed in initializer blocks.
class Employee(name: String) {    
init {        
logger.info("Employee initialized with value ${name}")    
}
}
I
f the constructor has annotations or visibility modifiers, the constructor{: .keyword } keyword is required, and the modifiers go before it:
class Employee public @Inject constructor(name: String) { ... }

 2)Secondary constructor :

Used inside class which are prefixed with constructor{: .keyword }:
class Employee {    
constructor(parent: Employee)
{        
parent.children.add(this)    
}
}

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 } keyword:
class Employee(val name: String) {    
constructor(name: String, parent: Employee) : this(name)
{        
parent.children.add(this)    
}
}
3)Creating instances or Objects of classes:
Kotlin doesn not have “new” keyword for creating object. Objects are created as shown below:
val employee = Employee() 
val student = Student("Joe Smith")

Some examples on class and objects :

Example1 :


Java code :

class Student{ 
int id;//field or data member or instance variable  
String name;  
 public static void main(String args[]){  
  Student s1=new Student();//creating an object of Student  
  System.out.println(s1.id);//accessing member through reference variable  
  System.out.println(s1.name);  
 }  



Kotlin Code :

class Student {
  var id:Int = 0//field or data member or instance variable 
  var name:String
  companion object {
 @JvmStatic fun main(args:Array<String>) {
      val s1 = Student()//creating an object of Student 
      println(s1.id)//accessing member through reference variable 
      println(s1.name)
    }
  }
}

Example 2 :

Java code :

class Rectangle{ 
 int length;  
 int width;  
 void insert(int l, int w){  
  length=l;  
  width=w;  
 }  
 void calculateArea(){System.out.println(length*width);}  
}  
class TestRectangle1{  
 public static void main(String args[]){  
  Rectangle r1=new Rectangle();  
  Rectangle r2=new Rectangle();  
  r1.insert(11,5);  
  r2.insert(3,15);  
  r1.calculateArea();  
  r2.calculateArea();  
}  



Kotlin Code :

class Rectangle {
  var length:Int = 0
  var width:Int = 0
  fun insert(l:Int, w:Int) {
    length = l
    width = w
  }
  fun calculateArea() {
    println(length * width)
  }
}
internal object TestRectangle1 {
  @JvmStatic fun main(args:Array<String>) {
    val r1 = Rectangle()
    val r2 = Rectangle()
    r1.insert(11, 5)
    r2.insert(3, 15)
    r1.calculateArea()
    r2.calculateArea()
  }
}



Tuesday, 30 May 2017

Variables and Data Types in Kotlin

Variables and Data Types in Kotlin :

In this tutorial we will learn how to declare variables in Kotlin. We are having java comparison code for easy and quick learning.

In kotlin all data types are defined with keyword var. There is no final 

Example 1 :

Java Code :

class A{  

private int data=50;
public String mData = "Test";
procted float test1 = 1.23;
private double test2 = 2.33; //instance variable  
public static final int FILES_TO_DOWNLOAD = 100 //static variable 

void method(){  
int n=90;//local variable  
}  

}//end of class 

Converted Kotlin Code : 

class A {

  private val data = 50
  var mData = "Test"
  var test1 = 1.23f
  private val test2 = 2.33//instance variable 

  fun method() {
    val n = 90//local variable 
  }

  companion object {
    val FILES_TO_DOWNLOAD = 100//static variable
  }

}//end of class

From Java To Kotlin - Your Cheat Sheet For Java To Kotlin



FromJavaToKotlin
From Java To Kotlin - Your Cheat Sheet For Java To Kotlin

Java
System.out.print("Amit Shekhar");
System.out.println("Amit Shekhar");
Kotlin
print("Amit Shekhar")
println("Amit Shekhar")

Java
String name = "Amit Shekhar";
final String name = "Amit Shekhar";
Kotlin
var name = "Amit Shekhar"
val name = "Amit Shekhar"

Java
String otherName;
otherName = null;
Kotlin
var otherName : String?
otherName = null

Java
if (text != null) {
  int length = text.length();
}
Kotlin
text?.let {
    val length = text.length
}

Java
String firstName = "Amit";
String lastName = "Shekhar";
String message = "My name is: " + firstName + " " + lastName;
Kotlin
val firstName = "Amit"
val lastName = "Shekhar"
val message = "My name is: $firstName $lastName"

Java
String text = "First Line\n" +
              "Second Line\n" +
              "Third Line";
Kotlin
val text = """
        |First Line
        |Second Line
        |Third Line
        """.trimMargin()

Java
String text = x > 5 ? "x > 5" : "x <= 5";
Kotlin
val text = if (x > 5)
              "x > 5"
           else "x <= 5"

Java
if (object instanceof Car) {
}
Car car = (Car) object;
Kotlin
if (object is Car) {
}
var car = object as Car

Java
if (object instanceof Car) {
   Car car = (Car) object;
}
Kotlin
if (object is Car) {
   var car = object // smart casting
}

Java
if (score >= 0 && score <= 300) { }
Kotlin
if (score in 0..300) { }

Java
int score = // some score;
String grade;
switch (score) {
 case 10:
 case 9:
  grade = "Excellent";
  break;
 case 8:
 case 7:
 case 6:
  grade = "Good";
  break;
 case 5:
 case 4:
  grade = "Ok";
  break;
 case 3:
 case 2:
 case 1:
  grade = "Fail";
  break;
 default:
     grade = "Fail";    
}
Kotlin
var score = // some score
var grade = when (score) {
 9, 10 -> "Excellent" 
 in 6..8 -> "Good"
 4, 5 -> "Ok"
 in 1..3 -> "Fail"
 else -> "Fail"
}

Java
for (int i = 1; i <= 10 ; i++) { }

for (int i = 1; i < 10 ; i++) { }

for (int i = 10; i >= 0 ; i--) { }

for (int i = 1; i <= 10 ; i+=2) { }

for (int i = 10; i >= 0 ; i-=2) { }

for (String item : collection) { }

for (Map.Entry<String, String> entry: map.entrySet()) { }
Kotlin
for (i in 1..10) { }

for (i in 1 until 10) { }

for (i in 10 downTo 0) { }

for (i in 1..10 step 2) { }

for (i in 10 downTo 1 step 2) { }

for (item in collection) { }

for ((key, value) in map) { }

Java
final List<Integer> listOfNumber = Arrays.asList(1, 2, 3, 4);

final Map<Integer, String> keyValue = new HashMap<Integer, String>();
map.put(1, "Amit");
map.put(2, "Ali");
map.put(3, "Mindorks");

// Java 9
final List<Integer> listOfNumber = List.of(1, 2, 3, 4);

final Map<Integer, String> keyValue = Map.of(1, "Amit",
                                             2, "Ali",
                                             3, "Mindorks");
Kotlin
val listOfNumber = listOf(1, 2, 3, 4)
val keyValue = mapOf(1 to "Amit",
                     2 to "Ali",
                     3 to "Mindorks")

Java
// Java 7 and below
for (Car car : cars) {
  System.out.println(car.speed);
}

// Java 8+
cars.forEach(car -> System.out.println(car.speed));

// Java 7 and below
for (Car car : cars) {
  if (car.speed > 100) {
    System.out.println(car.speed);
  }
}

// Java 8+
cars.stream().filter(car -> car.speed > 100).forEach(car -> System.out.println(car.speed));
Kotlin
cars.forEach {
    println(it.speed)
}

cars.filter { it.speed > 100 }
      .forEach { println(it.speed)}

Java
void doSomething() {
   // logic here
}
Kotlin
fun doSomething() {
   // logic here
}

Java
void doSomething(int... numbers) {
   // logic here
}
Kotlin
fun doSomething(vararg numbers: Int) {
   // logic here
}

Java
int getScore() {
   // logic here
   return score;
}
Kotlin
fun getScore(): Int {
   // logic here
   return score
}

// as a single-expression function

fun getScore(): Int = score

Java
int getScore(int value) {
    // logic here
    return 2 * value;
}
Kotlin
fun getScore(value: Int): Int {
   // logic here
   return 2 * value
}

// as a single-expression function

fun getScore(value: Int): Int = 2 * value

Java
public class Utils {

    private Utils() { 
      // This utility class is not publicly instantiable 
    }
    
    public static int getScore(int value) {
        return 2 * value;
    }
    
}
Kotlin
class Utils private constructor() {

    companion object {
    
        fun getScore(value: Int): Int {
            return 2 * value
        }
        
    }
}

// other way is also there

object Utils {

    fun getScore(value: Int): Int {
        return 2 * value
    }

}

Java
public class Developer {

    private String name;
    private int age;

    public Developer(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Developer developer = (Developer) o;

        if (age != developer.age) return false;
        return name != null ? name.equals(developer.name) : developer.name == null;

    }

    @Override
    public int hashCode() {
        int result = name != null ? name.hashCode() : 0;
        result = 31 * result + age;
        return result;
    }

    @Override
    public String toString() {
        return "Developer{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
Kotlin
data class Developer(var name: String, var age: Int)

Java
public class Utils {

    private Utils() { 
      // This utility class is not publicly instantiable 
    }
    
    public static int triple(int value) {
        return 3 * value;
    }
    
}

int result = Utils.triple(3);
Kotlin
fun Int.triple(): Int {
  return this * 3
}

var result = 3.triple()

Pojo class in kotlin