Wednesday, May 20, 2020

Null Safety , Lazy Keyword and LateInit Keyword

Null Safety :-

Safe call  ( ? )    use it if you don't mind getting null values
Not Null Insertion ( !! )  use if you are sure that value is not null otherwise throw Nullpointer Exception
Elvis ( ?: )  goes with function when values is not null, otherwise decided value
Safe call with let ( ?.Let { .. } ) execute the block only value is not null

In Android, we mostly use safe call and not null insertion.

eg :-

fun main(args:Array<String>) {
    var s: String? = null                //safe call

    println("The lenght of name is ${s?.length}")


    s?.let {                            //safe call with let
        println("The length of name is ${s.length}")
    }

    var len = {            // same below code as elvis
        if (s != null) 
            s.length
        else
            -1
    }

    var len1 = s?.length?:-1           //elvis
    println("The length of name is ${len1}")

    println("the length of name is ${s!!.length}")   //not null insertion
}

Lazy keyword :-

prevent unnecessary initialization of object.
can be var/val , null/not null and thread safe

 val pi: Float by lazy {
    3.14f
}

fun main (args:Array<String>)
{
 println("some initial code..")
 var a =pi*3*3
 var b = pi*a*a
 println("some more code...")
}


LateInit Keyword :-

Initialize the variable later, when used otherthrow uninitializedpropertyAccess Exception.
Allowed with only not null values
promise to compiler that value will initialize in Future 

** Mainly Helpful in Android Programming

fun main(args:Array<String>)
{
    var a = animal();
//    a.name = "Cat"
//println("name : ${a.name}")

    a.check()
}

class animal
{
    lateinit var name:String   //use of late init
    fun check()
    {
        name = "Monkey"
        println("name in function : ${name}")
    }
}



















Collections - [Array , List , Map, Set] / Filtering and Sorting

Array :-


fun main(args : Array<String>)
{
    var player = Array<String> (3){" "}  //initialization is necessary
    player[0]="Dhoni"
    player[1]="Sehwag"
    player[2]="Kohli"
//  player[9]="broad"  exception
    for(element in player)
    {
        println(element)
    }
    player[1]="KL Rahul"
    for(pl in 0..player.size-1)   //use of loop  Location wise
    {
        println(player[pl])
    }
    var num = Array<Int>(3){3}
    num[0]=55
    for(a in num)    //use of loop Directly
        println(a) 

}

List :-

fun main(args : Array<String>)
{
    var a = listOf<Int> (9,9,8)
    for(num in a)
    {
        println(num)
    }
//    for(num in 0..a.size-1)
    {
        println(a)
    }
   //  var b = mutableListOf<String>()
  //  var b = arrayListOf<Float>(5.9F, 6.7F,6.0F)
        var c = ArrayList<String> ()
        c.add("India")
        c.add("Pakistan")
        c.add("Isreal")

  //      c.remove("Pakistan")
   //     c.add(1,"Russia")

    c[1] = "Russia  n"
     for(element in c)
        println(element)
}


Map :-

fun main(args:Array<String>)
{
 //   var mymap =  mapOf<Int,String> ()

  // var abc = HashMap<Int,String> ()
  //  var abc = mutableMapOf<Int,String>()
    var abc = hashMapOf<Int,String>()
    abc.put(34,"cs")
    abc.put(12,"it")
    abc.put(89,"me")


    for(i in abc)
        println(i)

//    abc.put(12,"ko")
    abc.replace(12,"lm")


    for(key in abc.keys)
        println("Element at $key = ${abc[key]}")
}


Set :- 
contain unique value only no duplicates


fun main(args:Array<String>)
{
    var abc = hashSetOf<Int> (44,33,33,56,33,78,54,45)
    for(i in abc)
        println(i)

    var xyz = mutableSetOf<String>("aa","ab","cs","aa","aa","db","db")
    for (k in xyz)
        println(k)

    xyz.remove("db")
    xyz.add("kt")
    println("newc")

    for (k in xyz)
        println(k)
}

Filtering and Sorting :-

Filter and Map usage :-

Filter :-  filter our desired element out of collection.
Map :-  perform operation and modify elements.

eg :-

fun main(args : Array<String>)
{
    var mynum = listOf<Int>(2,3,4,8,66,55,99)

    var filt = mynum.filter { it<10 }   //filter usage  -- value less than 10
     for(i in filt)
      println(i)

    var mp = mynum.map { s -> s*s}  //map usage -- get new list square of previous one
     for(i in mp)
        println(i)

    println("both")

    var bth = mynum.filter { it<5 }.   //map and filter both usage 
                    map {it*it  }  //values less than 5 and square
    for(i in bth)
        println(i)

    println("In class")    //filter use in class created

    var per = listOf<person>(person("Lokesh",10),person("Vivek",14),person("Stranger",31),person("Lavish",19))

//    var myper =  per.filter {s->s.name.startsWith("L")}.map{it.name}
    var myper =  per.filter {it.age<20}.map{it.name}

    for(name in myper)
       println(name)
}

class person(var name:String, var age:Int)
{
    //some code
}

Predicates :-

'all' :-  Do all element satisfy the predicates/condition ?
'any' :-  Do any element satisfy the predicates/condition ?
'count' :- Total element that satisfy the predicates
'find' :- Return the First element that satisfy the Predicates


fun main(args:Array<String>)
{
    val numT = listOf<Int>(3,4,6,7,1,56,2,55,66,67,43,23)

    val fn = {s:Int -> s > 10}

    var check1 = numT.all(fn)    //output false  
    println(check1)

    var check2 = numT.any{s -> s>10}   //output true  
    println(check2)

    var count1:Int = numT.count{it>10}   //output 6 
    println(count1)

    var num1 = numT.find(fn)   //output 56 
    println(num1)
}




Lambdas and it uses

Lambdas :- (High level Function)

can accept function as Parameter
can return Function as Parameter
or can do both

fun main(args : Array<String>)
{
    var addy : (Int,Int) -> Int = {x,y ->x+y}
    var a = show()
     a.see(7,8,addy)    //all  3 are same
    a.see(10,20,{x,y ->x+y})
    a.see(45,73) {x,y ->x+y}
}

class show
{
    fun see(a:Int,b:Int,action:(Int,Int)->Int)
    {
        var result = action(a,b)
        println(result)
    }
}

It :-

Implicit name of Single Parameter

fun main(args:Array<String>)
{
val program = Program()
program.reverseanddisplay("Hello,{it.reversed()})   //use of it

}

class Program(str : String, myFunc : (String) -> String) {
var result = myFunc(str)
println(result) }}
























Data Class , Object Declaration and Companion Object

Data class :-

Contain method such hashcode(), equal(), to String() ,copy()- BuiltIn
In data class, primary constructor contain variable(properties)

fun main(Args : Array<String>)
{
var user1 = user("sum",10)
var user2 = user("sum",10)
println(user1.toString())    //using inbuilt function of the data class (print everything!!) 

if(user1 == user2)
println("equals")
else
println("not equals")

var newuser  = user1.copy(id=25)  //copy the id to new instance
prinln(newuser)
}

data class user(var name:String,var id:String)  //this is data class

Object Declaration :-

Acted as class having static method and Variables
use keyword 'Object'
Cannot have constructor
can have superclass & init

fun main(args:Array<String>){
    customerdata.count = 98
    println(customerdata.count)
    customerdata.count =22
    println(customerdata.count)
    println(customerdata.type())
  customerdata.mymethod("Hello")}

open class supera{
    open fun mymethod() {
        println("mysuperclass") }}

object customerdata : supera(){   //object declaration
var count:Int = -1   //behaves like static method
 fun type():String {
        return "Indian"}

  fun mymethod(input:String) {   //behaving like static method
 super.mymethod()
        println(input)}}


Companion Object :- 

Same as object , but declared within class


fun main(args : Array<String>){
    my_class.count =78
    println(my_class.count)
    println(my_class.customer_type())}

class my_class{
    companion object{
        var count : Int = -1
 fun customer_type():String {
           return "Indian" } }}



















Inheritance,Overiding,Visibility Modifier, Abstract class & Interface

Inheritance :-

Default class in kotlin :- Public and Final(member can't derived)
make class open for Inheritance

eg-1

open class ABC {  //parent class (open)
   fun think () {
      print("Hey!! i am thiking ")
   }
}
class BCD: ABC(){ // inheritence happend (child class)
}

class MCD:ABC() {  //Inherit parent class method also have its own method
fun doing() {
print("I am doing")
}

fun main(args: Array<String>) {
   var  a = BCD()
   a.think()
   var b =MCD()
   b.think()
   b.doing()
}


Overiding :-
child class method want to work in its own ways
super is used to call parent method


open class Animal{
open var color : Stirng = "White"
   open fun eat () {
      print("Animal Eating")
   }
}

class dog: Animal() { // inheritance happens
var breed : String = "labrador"
override var color = "Black"

fun bark()
{
print("Dog barking")
}
   override fun eat() {
   super<Animal>.eat()   //executing parent method also
      print("Dog Eating")
   }
}
fun main(args: Array<String>) {
   var  doga = dog()
   doga.eat()
   doga.bark()
}


Overiding in Constructor :-

Primary Constructor

main()
var dog =  Dog("Black","png")

open class Animal(var color:String)
init {
print("from animal Init : $color) }}

class dog (color:String, var breed:String):Animal(color) {
init {
print("from Dog Init : $color and $breed) }}

Secondary Constructor

open class Animal {
var color : String = " "
constructor(color : String) : this() {
this.color = color }}

class Dog: Animal {
var breed:String =  " "
constructor(color: String, breed: String): super(color) {
this.breed = breed }


Visibility Modifier

Public -  By Default in Kotlin
Protected - Not applicable to High level Function or classes - Visible in sub class
Internal - Visible within same  module (within project)
Private - Visible inside ____.kt


open class Person {
private val a = 1
protected val b = 2
internal val c = 3
val d  = 10 //public by default }

within Inherit class

class India : Person() {
// a is not visible
//b,c,d are visible
}

within different class in same package

class Textclass  {
//person.a, person.b are not visible //private and protected
//person.c, person.d are visible //public and internal  }


Abstract - Classes/Method/Properties :-
-can't create instance/object of Abstract class
-need to overide Abstract method,properties inside Derived class

abstract class Person {   //can defined instance of abstract class
  abstract var name : String
  abstract fun eat()       //abstarct properties is open by default
  open fun getHeight() { }  //'open' function ready to overridden
  fun gotoSchool()   { } //Normal funtion public & final by default
}

class Indian: Person() {
overide var name : String
overide fun eat() {
//own code
}
}


Interface :-
-it is not class
-can not Instantiated
-have 2 method with same name, we have to overide them.
        super<interfacename>.method
-can normal and abstract method

main() {
var myButton = MyButton()
myButton.onTouch()
myButton.onClick() }

interface MyInterfaceListener {   //can't create Instance
fun onTouch()  //Method in interface is Abstract by Default
fun onClick()  {  //Normal method are public and open by Default , but not final
println("FirstInterface :- on click") }

interface MySecondInterface {
fun onTouch() {
println("SecondInterface :- on Touch")
fun onClick()  {
println("SecondInterface :- on click") }


class MyButton :  MyInterfaceListener,MySecondInterface  {
overide fun onclick() {
super<MyInterfaceListener>.onClick()
super<MySecondInterface >.onTouch() }

overide fun onTouch() {
super.onTouch()  }}  //executes by order, takes first Interface




Tuesday, May 19, 2020

Constructor


Constructor :-

  • init Block  //code automatically run
  • Primary Constructor
  • Secondary Constructor  // have more than one secondary constructor

Primary Constructor :-

eg-1

//main function
fun main(args: Array<String>)
{
    val add = Add(5, 6)
    println("The Sum of numbers 5 and 6 is: ${add.c}")
}
//primary constructor
class Add constructor(a: Int,b:Int) //a and b can't be access from main
{
    var c = a+b;
}


eg-2

fun main(args: Array<String>) {
    val emp = employee(18018, "Sagnik")
}
class employee(emp_id : Int , emp_name: String) {
    val id: Int
    var name: String
  
    // initializer block
    init {
        id = emp_id
        name = emp_name
  
        println("Employee id is: $id")
        println("Employee name: $name")
    }
}

output:-
Employee id is: 18018 Employee name: Sagnik


Secondary Constructor :-

Prefix with Constructor
Allow initialization of variables 
Allow to provide some logic to the class as well

eg-1

fun main(args: Array<String>) {
    employee(18018, "Sagnik")
    employee(11011,"Praveen",600000.5)
}
class employee {
  
      constructor (emp_id : Int, emp_name: String ) {
          var id: Int = emp_id
          var name: String = emp_name
          print("Employee id is: $id, ")
          println("Employee name: $name")
          println()
      }
  
       constructor (emp_id : Int, emp_name: String ,emp_salary : Double) {
           var id: Int = emp_id
           var name: String = emp_name
           var salary : Double = emp_salary
           print("Employee id is: $id, ")
           print("Employee name: $name, ")
           println("Employee name: $salary")
       }
}


output:-
Employee id is: 18018, Employee name: Sagnik Employee id is: 11011, Employee name: Praveen, Employee name: 600000.5

Null Safety , Lazy Keyword and LateInit Keyword

Null Safety :- Safe call  ( ? )    use it if you don't mind getting null values Not Null Insertion ( !! )  use if you are sure that val...