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




























No comments:

Post a Comment

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