Android Tutorial

Software Setup and Configuration

Android Studio

File Structure

Components

Core Topics

Layout

View

Button

Intent and Intent Filters

Toast

RecyclerView

Fragments

Adapters

Other UI Component

Image Loading Libraries

Date and Time

Material Design

Bars

Working with Google Maps

Chart

Animation

Database

Advance Android

Jetpack

Architecture

App Publish

App Monetization

Switch in Kotlin

In Kotlin, the switch statement from languages like Java is replaced by the when expression. It offers more flexibility and functionality than the traditional switch.

Basic Usage:

Here's an example of using when as a replacement for switch:

fun main() {
    val x = 3

    when (x) {
        1 -> println("x is 1")
        2 -> println("x is 2")
        3 -> println("x is 3")
        else -> println("x is neither 1, 2, nor 3")
    }
}

Using Multiple Conditions:

You can check for multiple conditions in a single branch:

when (x) {
    1, 2 -> println("x is 1 or 2")
    3 -> println("x is 3")
    else -> println("x is neither 1, 2, nor 3")
}

Using Ranges:

when (x) {
    in 1..10 -> println("x is between 1 and 10")
    !in 10..20 -> println("x is not between 10 and 20")
    else -> println("x is something else")
}

Using Expressions:

when can also be used with expressions:

val str = "Hello"

when (x) {
    str.length -> println("x is the length of the string 'str'")
    else -> println("x is something else")
}

Using when as an Expression:

You can also use when as an expression where it returns a value:

val description = when (x) {
    1 -> "One"
    2 -> "Two"
    3 -> "Three"
    else -> "Unknown"
}

println(description) // This will print "Three" for x = 3

Replacing if-else chains:

The when expression can also be used as a replacement for lengthy if-else chains:

when {
    x < 5 -> println("x is less than 5")
    x % 2 == 0 -> println("x is even")
    else -> println("x is something else")
}

As demonstrated, the when expression in Kotlin is a powerful construct that provides a concise way to handle multiple conditions.

  1. Using when expression as a switch in Kotlin:

    • Description: Demonstrates the Kotlin when expression as a replacement for traditional switch statements.
    • Example Code (Kotlin):
      when (condition) {
          1 -> println("Case 1")
          2 -> println("Case 2")
          else -> println("Default case")
      }
      
  2. Switch vs when in Kotlin:

    • Description: Contrasts the traditional switch statement in other languages with Kotlin's versatile when expression.
    • Example Code (Kotlin):
      // Switch in Java
      switch (number) {
          case 1: System.out.println("Case 1");
          break;
          case 2: System.out.println("Case 2");
          break;
          default: System.out.println("Default case");
      }
      
      // Equivalent in Kotlin using when
      when (number) {
          1 -> println("Case 1")
          2 -> println("Case 2")
          else -> println("Default case")
      }
      
  3. Switch case with multiple conditions in Kotlin:

    • Description: Handles multiple conditions within a single when expression.
    • Example Code (Kotlin):
      when (condition) {
          in 1..5 -> println("Case 1 to 5")
          10, 20 -> println("Case 10 or 20")
          else -> println("Default case")
      }
      
  4. Switch with enum in Kotlin:

    • Description: Utilizes when with enums for concise and readable code.
    • Example Code (Kotlin):
      enum class Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY }
      
      val day = Day.MONDAY
      when (day) {
          Day.MONDAY -> println("It's Monday")
          Day.TUESDAY, Day.WEDNESDAY -> println("It's a workday")
          else -> println("It's the weekend")
      }
      
  5. Handling default case in Kotlin switch:

    • Description: Ensures a default case is executed when none of the specified conditions match.
    • Example Code (Kotlin):
      when (condition) {
          1 -> println("Case 1")
          2 -> println("Case 2")
          else -> println("Default case")
      }
      
  6. Switch statement for string values in Kotlin:

    • Description: Illustrates using when with string values for efficient string-based decision-making.
    • Example Code (Kotlin):
      val day = "Monday"
      when (day) {
          "Monday" -> println("It's Monday")
          "Tuesday", "Wednesday" -> println("It's a workday")
          else -> println("It's the weekend")
      }
      
  7. Switch with ranges in Kotlin:

    • Description: Utilizes ranges in when for concise and expressive comparisons.
    • Example Code (Kotlin):
      val score = 75
      when (score) {
          in 0..50 -> println("Fail")
          in 51..75 -> println("Pass")
          in 76..100 -> println("Excellent")
          else -> println("Invalid score")
      }
      
  8. Switch expression in Kotlin vs Java:

    • Description: Compares switch expressions in Kotlin and Java, showcasing Kotlin's more expressive syntax.
    • Example Code (Kotlin/Java):
      // Kotlin switch expression
      val result = when (condition) {
          1 -> "Case 1"
          2 -> "Case 2"
          else -> "Default case"
      }
      
      // Java switch statement
      String result;
      switch (condition) {
          case 1:
              result = "Case 1";
              break;
          case 2:
              result = "Case 2";
              break;
          default:
              result = "Default case";
      }
      
  9. Switching between multiple types in Kotlin:

    • Description: Demonstrates how when can handle various types, making it more versatile.
    • Example Code (Kotlin):
      val value: Any = 42
      when (value) {
          is String -> println("It's a String")
          is Int -> println("It's an Int")
          else -> println("Unknown type")
      }
      
  10. Nested switch statements in Kotlin:

    • Description: Illustrates nesting when expressions for complex decision trees.
    • Example Code (Kotlin):
      when (condition) {
          in 1..5 -> {
              when (subCondition) {
                  1 -> println("Nested case 1")
                  2 -> println("Nested case 2")
              }
          }
          10, 20 -> println("Case 10 or 20")
          else -> println("Default case")
      }
      
  11. Switching on custom objects in Kotlin:

    • Description: Enables switching on custom objects for more structured decision-making.
    • Example Code (Kotlin):
      data class Color(val name: String)
      
      val color = Color("Red")
      when (color) {
          Color("Red") -> println("It's a red color")
          Color("Blue") -> println("It's a blue color")
          else -> println("Unknown color")
      }
      
  12. Switch statement alternatives in Kotlin:

    • Description: Explores alternative constructs in Kotlin that can be used instead of when.
    • Example Code (Kotlin):
      // Using if-else as an alternative to switch
      val result = if (condition == 1) "Case 1" else if (condition == 2) "Case 2" else "Default case"
      
      // Using a Map for mapping values to actions
      val actionMap = mapOf(1 to "Action 1", 2 to "Action 2")
      val result = actionMap[condition] ?: "Default action"
      
  13. Pattern matching with when in Kotlin:

    • Description: Introduces pattern matching with when in Kotlin for more advanced matching scenarios.
    • Example Code (Kotlin):
      val result = when (val response = fetchData()) {
          is Success -> "Data fetched successfully"
          is Error -> "Error fetching data: ${response.message}"
      }