History


Philosophy of Kotlin

a statically typed language for multiple applications.

Concise

Safe

Interoperable

Tool friendly


Kotlin & Byte Code

Keywords


Variables


String


Constants

val a = "RED" const val a = "RED"
converted intoprivate static final String a = "RED"; converted into public static final String a = "RED";
also create a get Function does not create and value is evaluted at compile.
slow fast

Function


Manage Null

here are code with different cases

    var a : String? = null
    println(a) // print null
    println(a?.length) // print null, you can not use a.length as a is nullable  
    println(a?.length ?: -1 ) // print -1 (Elvis operator )
    println(a!!.length) // Cause Kotlin NuLLPointerException.u can use try-catch to handle it 


Iterate over Collection

fun main(args: Array<String>) {

    val arr = arrayOf(1,2,3,4,5)

    for(item in arr){
        println(item) // print each item in a new line
    }

    // until stop at max -1 (i.e max is excluded)
    for (index in 0 until arr.size){
        println(arr.get(index))  // print each item in a new line
    }

    // indices return array of index, step 2 means to update each iteration with 2 
    for(index in arr.indices step  2 ){
        println(arr.get(index))
    }
}


Exception


Create Library


Class


Mix Kotlin & Java


Packages


Collections

    // this is Immutable list so can not add/remove from it
    val list = listOf("Ahmed" , "Mahmoud")
    // this is mutable list
    val mulList = mutableListOf("Ahmed" , "Mahmoud")
    mulList.add("Hafez")
    mulList.add(0 , "Hassan")
    mulList.remove("Ahmed")
    println(mulList) // [Hassan, Mahmoud, Hafez]

    // this is Immutable Set so can not add/remove from it
    val set = setOf(1,2,3,2,4,5)
    // this is mutable Set
    val mulset = mutableSetOf<Int>(1,2,3,2,4,5)
    println(mulset) // [1, 2, 3, 4, 5] NOTE 2 is displayed only one time

    // this is mutable Map
    val map = mutableMapOf(Pair("Ahmed" , 22) , Pair("Mahmoud" , 23))
    // put is used to add Pairs(Key , Value)
    map.put("Hassan" , 21 )
    // display values is by calling get(key) or use this trick
    for ((name , age) in map) println(" name : $name and Age is $age")


Inheritance

open class Animal (val color: String) {
    fun walk(){
        println("I am Walking")
    }

    override fun  toString(): String {
        return "Animal with ${color}"
    }
}

class Dog(color: String) : Animal(color ){

    override fun  toString(): String {
        return super.toString() + this::class.simpleName
    }
}


Interface


Lambda Expression


data class


abstract & sealed class


Thanks to Allah, last update 23/9/2019

Flag Counter