Skip to main content


Showing posts from April 1, 2019

Kotlin - Control Flow - when

Greetings! Just like if, when also an expression. It has 2 forms. With a value - behave as a switch operator. Without a value - behave as if-else-if chain. when as a switch Java private void dayOfWeek(int dayOfWeek) { switch (dayOfWeek) { case 1: System.out.println("Sunday"); break; case 2: System.out.println("Monday"); break; case 3: System.out.println("Tuesday"); break; case 4: System.out.println("Wednesday"); break; case 5: System.out.println("Thursday"); break; case 6: System.out.println("Friday"); break; case 7: System.out.println("Saturday"); break; default: System.out.println("Invalid day"); } } Kotlin private fun dayOfWeek(dayOfWeek: I

Kotiln - Control Flow - If

Greetings! If is the most basic way to control flow in Kotlin. Unlike Java, in Kotlin if is an expression. That is it return a value. Statement - is a program instruction that return no value. Can't be on right side of the equal sign. Expression - is a program instruction that return values. Can be assign to a variable. Java private void findMax(int a, int b) { int max; if (a > b) { max = a; } else { max = b; } System.out.println("Max value is " + max); } Kotlin (traditional statement) private fun findMax(a: Int, b: Int) { val max: Int if (a > b) { max = a } else { max = b } println("Max value is $max") } Kotlin (as an expression) private fun findMax(a: Int, b: Int) { val max: Int = if (a > b) { a } else { b } println("Max value is $max") } Ternary Operator Kotlin doesn't have a ternary operator. It's bec