Basic Syntax in Kotlin | Tutorial-3(2)

Basic Syntax in Kotlin | Tutorial-3(2) Continue............ 


Using type checks and automatic casts:
The isoperator checks if an expression is an instance of a type. If an immutable local variable or property is checked for a specific type, there's no need to cast it explicitly:

 fun getStringLength(obj: Any): Int? {  
     if (obj is String) {  
     // `obj` is automatically cast to `String` in this branch  
     return obj.length  
     }  
     // `obj` is still of type `Any` outside of the type-checked branch  
     return null  
 }  
 fun main(args: Array<String>) {  
   fun printLength(obj: Any) {  
     println("'$obj' string length is ${getStringLength(obj) ?: "... err, not a string"} ")  
   }  
   printLength("Incomprehensibilities")  
   printLength(1000)  
   printLength(listOf(Any()))  
 } 
 
 Result:  
 'Incomprehensibilities' string length is 21  
 '1000' string length is ... err, not a string  
 '[java.lang.Object@6b884d57]' string length is ... err, not a string  

OR

 fun getStringLength(obj: Any): Int? {  
       if (obj is String) return null  
       // `obj` is automatically cast to `String` in this branch  
       return obj.length  
     }  
 }  
 fun main(args: Array<String>) {  
   fun printLength(obj: Any) {  
     println("'$obj' string length is ${getStringLength(obj) ?: "... err, not a string"} ")  
   }  
   printLength("Incomprehensibilities")  
   printLength(1000)  
   printLength(listOf(Any()))  
 } 
 
 Result:  
 'Incomprehensibilities' string length is 21  
 '1000' string length is ... err, not a string  
 '[java.lang.Object@6b884d57]' string length is ... err, not a string  

OR EVEN

 fun getStringLength(obj: Any): Int? {  
       // obj` is automatically cast to `String` on the right-hand side of `&&`  
       if (obj is String && obj.length > 0) {  
       return obj.length  
     }  
     return null  
 }  
 fun main(args: Array<String>) {  
   fun printLength(obj: Any) {  
     println("'$obj' string length is ${getStringLength(obj) ?: "... err, is empty or not a string at all"} ")  
   }  
   printLength("Incomprehensibilities")  
   printLength("")  
   printLength(1000)  
 }  

 Result:  
 'Incomprehensibilities' string length is 21  
 '' string length is ... err, is empty or not a string at all  
 '1000' string length is ... err, is empty or not a string at all  


Using a for loop:
 fun main(args: Array<String>) {  
   val items = listOf("apple", "banana", "kiwi")  
   for (item in items) {  
     println(item)  
   }  
 }  

 Result:  
 apple  
 banana  
 kiwi  

OR

 fun main(args: Array<String>) {  
    val items = listOf("apple", "banana", "kiwi")  
    for (index in items.indices) {  
     println("item at $index is ${items[index]}")  
   }  
 }  

 Result:  
 item at 0 is apple  
 item at 1 is banana  
 item at 2 is kiwi  

Using a while loop:
 fun main(args: Array<String>) {  
    val items = listOf("apple", "banana", "kiwi")  
    var index = 0    
    while (index < items.size) {  
     println("item at $index is ${items[index]}")  
     index++  
   }  
 }  

 Result:  
 item at 0 is apple  
 item at 1 is banana  
 item at 2 is kiwi  


Using when expression
 fun describe(obj: Any): String =  
   when (obj) {  
   1     -> "One"  
   "Hello"  -> "Greeting"  
   is Long  -> "Long"  
   !is String -> "Not a string"  
   else    -> "Unknown"  
 }  
 fun main(args: Array<String>) {  
   println(describe(1))  
   println(describe("Hello"  
   println(describe(1000L))  
   println(describe(2))  
   println(describe("other"  
 }  

 Result:  
 One  
 Greeting  
 Long  
 Not a string  
 Unknown  


Using ranges
Check if a number is within a range using in operator:
 fun main(args: Array<String>) {  
   val x = 10  
   val y = 9  
   if (x in 1..y+1) {  
     println("fits in range")  
   }  
 }  
Result:fits in range


Result:fits in range
Check if a number is out of range:
 fun main(args: Array<String>) {  
   val list = listOf(""a", "b", "c"  
   if (-1 !in 0..list.lastIndex) {  
     println("-1 is out of range")  
   }  
   if (list.size !in list.indices) {  
     println("list size is out of valid list indices range too")  
   }  
 }  

 Result:  
 -1 is out of range  
 list size is out of valid list indices range too  

Iterating over a range:
 fun main(args: Array<String>) {  
   for (x in 1..5) {  
     print(x)  
   }  
 } 
 
 Result:12345  

OR over a progression:
 fun main(args: Array<String>) {  
   for (x in 1..10 step 2) {  
     print(x)  
   }  
   for (x in 9 downTo 0 step 3) {  
     print(x)  
   }  
 }  

 Result:135799630  


Using collections
Iterating over a collection:
 fun main(args: Array<String>) {  
   val items = listOf("apple", "banana", "kiwi"  
   for (item in items) {  
     println(item)  
   }  
 }  

 Result:  
 apple  
 banana  
 kiwi  


Checking if a collection contains an object using inoperator:
 fun main(args: Array<String>) {  
   val items = setOf("apple", "banana", "kiwi"  
   when {  
     "orange" in items -> println("juicy"  
     "apple" in items -> println("apple is fine too"  
   }  
 }  

 Result:apple is fine too  



Using lambda expressions to filter and map collections:
 fun main(args: Array<String>) {  
    val fruits = listOf("banana", "avocado", "apple", "kiwi"  
    fruits  
   .filter { it.startsWith("a" }  
   .sortedBy { it }  
   .map { it.toUpperCase() }  
   .forEach { println(it) }  
 }  

 Result:  
 APPLE  
 AVOCADO  



-----------END-----------










Comments