Tuesday, May 19, 2020

Kotlin Functions

Basic Example :-

fun addNumbers(n1: Double, n2: Double): Int {   //Int is Returntype
    val sum = n1 + n2
    val sumInteger = sum.toInt()
    return sumInteger
}

fun addNumbers(n1: Double, n2: Double): Unit { //Returning Nothing & can be blank also
    val sum = n1 + n2                                                            (No need to define)
    val sumInteger = sum.toInt()
    return sumInteger
}

Function as Expression :-

fun max(a:Int, b:Int):Int {
if (a >b ) {
return a
}
else {
return b 
}
}

can be changed into -

fun max(a:Int, b:Int):Int = if (a>b) a else b


Default Function :- Interpolation

- Takes Default value when no arguments is passed.

main()

var result = findVolume(2,3)   //here takes default h as 10
print(result)


var result = findVolume(2,3,8)  //values already provided , so no default taken
print(result)


fun findVolume(l:Int,b:Int,h:Int=10) {  //takes default h as 10 if not provided
return l*b*h }


Named Parameter :-

No matter with sequence of arguments in function.
Name of Arguments will be same in calling and called function.

main()
findVolume(h=30,b-=5,l=7)
findVolume(b=22,l=9)

fun findVolume(l:Int,b=int,h:Int=10) {  //No matter of sequence, Default parameter also provided
print(lenght $l)
print(breadth $b)
print(height $h)
}

Extension Function :-

Add new function to any class in main.
New function will be static.

eg-1

main()  {
var student = Student()
println("passed status :" +student.ispassed(57)) 
println("passed status :" +student.isScholar(57))  }
 

fun Student.isScholar(mark :Int):Boolean {  //This is extension function
return mark > 95 }

class Student {
fun ispassed(mark : Int) : Boolean {
return mark > 40 }


main() {
var str1 = "man"
var str2 = "eats"
var str3 = "apple"
println(str3.add(str1,str2) 

fun String.add(s1:String,s2.String):String { //extension function 
return this + s1 + s2 }

*Extenstion function work String, Int etc as datatype is class in Kotlin


Infix Function :-
Same as Extension Function but work with Single Parameter.
prefix of Infix

main() {
val x:Int = 6
val y:Int = 10
val greaterVal = x greater y   //x.greater(y) new way of defining fun
println(greaterVal)

infix funtion Int.greater(other.Int) : Int {
if (this>other) 
return this
else
return other } }

Tailrec Fuction :-   
use Recursion.(calling function within own function)
Avoid Stackoverflow exception


tailrec fun findFixPoint(x: Double = 1.0): Double
        = if (Math.abs(x - Math.cos(x)) < eps) x else findFixPoint(Math.cos(x))





Monday, May 18, 2020

Kotlin Basics-2


Ranges :-

  1. val r1 = 1..9    // 1 2 3 4 5 6 7 8 9
  2. val r2 =  1..10 step 2  // 1 3 5 7 9
  3. val r3 = 5 downTo 1 // 5 4 3 2 1
  4. val r4 = 5 downTo 1  step 2  // 5 3 1
  5. val r5 = 'a'..'z'    // a b c .............. z
  6. var isPresent  =  a in r5 // true/false
  7. var countdown 10.downTo(1)  //10 9 8 7 6 5 4 3 2 1
  8. var moveup 1.rangeTo(10)  // 1 2 3 4 5 6 7 8 9 10


If expression :-

// Traditional usage 
var max = a 
if (a < b) max = b

// With else 
var max: Int
if (a > b) {
    max = a
} else {
    max = b
}
 
// As expression 
val max = if (a > b) a else b

When Expression :-


when (x) {
    1 -> print("x == 1")
    2 -> print("x == 2")
    else -> { // Note the block
        print("x is neither 1 nor 2")
    }
}

when (x) {
    0, 1 -> print("x == 0 or x == 1")
    else -> print("otherwise")
}

when (x) {
    in 1..10 -> print("x is in the range")
    in validNumbers -> print("x is valid")
    !in 10..20 -> print("x is outside the range")
    else -> print("none of the above")
}

Iterators : For/While/Do While 

For :-

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

for (i in array.indices) {
    println(array[i])
}

While :-

while (x > 0) {
    x--
}


DoWhile :-

do {
    val y = retrieveData()
} while (y != null) 


Break :-

 Terminates the nearest enclosing loop.
//out of Loop

if ( i in 1..3)
{
for (j in 1..3)
{
println("$i $j")
if(i==2 && j==2)
break
}
}

output :- 1.1 1.2 1.3 2.1 2.2 3.1 .3.2 3.3
//discontinue after 2.2 from inner loop

Continue :-

Proceeds to the next step of the nearest enclosing loop.
//miss the step continue from next Step



if ( i in 1..3)
{
for (j in 1..3)
{
if(i==2 && j==2)
continue
println("$i $j")
}
}

output :- 1.1 1.2 1.3. 2.1 2.3 3.1 3.2 3.3
//skip the 2.2 due to continue & goes to first statement of same loop


Break and Continue with Labels :- 

continue at particular steps


outer@ if ( i in 1..3)
{
for (j in 1..3)
{
if(i==2 && j==2)
continue @outer
println("$i $j")
}
}

// 1.1 1.2 1.3 2.1 3.1 3.2 3.3
//after 2.2 , it continue from outer loop again




























Kotlin basics

Kotlin tutorial :-

Extraordinary Features :-

Support Null Pointer Exception
Support Immutability


Basic Program :-

fun main (args : Array<String>) {
println("Hello World")
}

Comment :-

//This is inline comment

/* multiple line comment 1
    multiple line comment 2  */

Variable :-

var  -  mutable
val - Immutable

String Interpolation :-

class person { }

main()
var personobj = person()

//String Interpolation
println("name of person ${personobj.name}")
}

Datatypes:-

var age : Int = 10

//age  =  variable names
//Int = data type

1. Numbers – Byte, Short, Int, Long, Float, Double
2. Boolean – True, false
3. Characters
4. Arrays
5. Strings

//Depends upon the Size

String Interpolation :-    (More Example)

eg-1

val  a = 20
val b = 10

println("Sum ${a+b}")

eg-2

class rectangle {
rec.len : Int = 0
rec.bre : Int = 0 }

main()

var rec=rectangle()
rec.len = 5
rec.bre =9

println("lenght of rectangle is ${rec.len} and breadth of rectangle is ${rec.bre}
              and Area is ${rec.len * rec.bre})







   



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...