DEV Community

Cover image for When I prefer use when then if-else in Kotlin
Mateus Malaquias
Mateus Malaquias

Posted on

2 1

When I prefer use when then if-else in Kotlin

TL;DR

  • if-else for simple cases with only one conditions or to use early returns pattern.
  • when for more complex cases with multiple conditions and to have a cleaner code.

Ever feel lost in a maze of if-else statements, desperately trying to handle every input nuance? Fear not, fellow dev! Kotlin's when statement offers a sleek and powerful escape route.
Forget the Java switch cases or the endless else if that makes your code's readability horrible. when can simplify your logic, writing multiple conditions into a single and clear block.

Why when is better in my option?

  • Clean Code: allows you to write more concise and readable code, especially when you need to check multiple conditions.

  • Type Safe: runtime mistakes can be avoided by checking the expression against each case value.

  • Extensibility: can be easily extended to handle new cases.

Code example

fun renderRequests(userId: String) = renderComponent {
  val user = getUser(userId)
    when (user.role) {
      is ROLE.CHILD -> return
      is ROLE.UNCLE -> defaultRequestError()
      is ROLE.PARENT -> {
        buildRenderComponent(user)
      }
    }
}
Enter fullscreen mode Exit fullscreen mode

Now compare with if-else:

fun renderRequests(userId: String) = renderComponent {
  val user = getUser(userId)
   if (user.role == ROLE.CHILD) {
    return
   } else if (user.role == ROLE.UNCLE) {
    defaultRequestError()
   } else if (user.role == ROLE.PARENT) {
    buildRenderComponent(user)
   }
}
Enter fullscreen mode Exit fullscreen mode

When if-else is a better option?

When I want to use early returns pattern.

Writing functions or methods, early return means that the expected positive result is returned at the end of the function, and when conditions are not met, the rest of the code ends the execution by returning or throwing an exception.

Code example

fun sayMyName(name: String): String {
 if (!name || name.length < 0) {
    return;
  }
  return `Hello, ${name}`
}
Enter fullscreen mode Exit fullscreen mode

References

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay