if statements:
val num = 21 if (num < 21) { println("Underage drinker") } else { println("Adult") } // Output: Adult Assigning variable with outcome of 'if' statement: // 'age' will be assigned the string after the println() val age = if(num < 21) { printlln("Underage drinker") "Do not allow drinking" // if 'num' is under 21, 'age' assigned "Do not allow drinking" } else { println("Legal drinker") // 'num' is over 21, 'age' assigned "Allow drinking" "Allow drinking" } Using 'if' statement as an expression // corresponding else clause is mandatory when using 'if' as an expression println(if (a > b) "a is greater than b" else "a is less than b") when statements:
val cost = 100 when(cost) { 0 -> println("Free admission") 50 -> println("Half-price admission") 51..99 -> println("Over 50% off admission") else -> println("Full-price admission") // default } // Output: Full-price admission Assigning variable with outcome of 'when' statement: // 'admission' will be assigned the appropriate string based on corresponding 'when' condition val admission = when(cost) { 0 --> "Free admission" 50 --> "Half-price admission" 51..99 --> "Over 50% off admission" else ---> "Full-price admission" } while & do-while loops: // while loops in Kotlin have similar syntax to Java val num = 0 while(i <10) { println("$num ") num++ } do { println(num) num++ } while(num < 20) for loops: for(i in 1..20) { print("$i ") } // or, the above simplified: // Output: Integer range of 1-20 (e.g. 1 2 3 4 5...etc, includes 100) for(i in 1..100) print("$i ") // Output: same as above, but excludes end number 100) for(i in 1 until 100) print("$i ") for(chars in "Kotlin language") { print("$chars ") } // Output: Each character of string w/ space between each character (e.g. K o t l i n l a n g .. etc) Using downTo operator in 'for' condition, reverses range of output for(i in 100 downTo 1) { print("$i ") } // Output: 100, counting down by 1 (e.g. 100 99 98 97 .. etc) Using downTo operator + step for(i in 100 downTo 1 step 5) { print("$i ") } // Output: 100, counting down by 5-step increments (e.g. 100 95 90 85 .. etc) Looping through an array for(item in numArray) { println("$item is an item in numArray") } Looping through an array using its index for((index, item) in numArray.withIndex()) { println("numArray[ $index ] has the element $item) } Looping through a string to print each of its characters val language = "Kotlin" for(c in language) { print(c) } Comments are closed.
|
AuthorExploring Android and mobile web design, security, and development. Archives
March 2021
Categories |