If and Try-Catch as Expressions
Swipe to show menu
In Java, you are accustomed to if and try-catch being statements, meaning they can control the flow of your program but do not directly produce a value. This leads to patterns such as using the ternary operator (condition ? value1 : value2) for conditional assignments, or initializing variables before a try-catch block and assigning them within. Kotlin takes a different approach: both if and try-catch are expressions, not just statements. This means they can be used directly to assign values, making your code more concise and eliminating the need for a ternary operator entirely.
When you use if as an expression, it evaluates to a value that you can assign directly to a variable. Similarly, a try-catch block can return a value, allowing you to handle exceptions and provide fallback results in a single, readable construct. This expressive power is one of the reasons Kotlin code often appears more streamlined compared to Java.
Main.kt
123456789101112131415161718192021package com.example fun riskyOperation(): Int { throw Exception("Failure!") } fun main() { val number = 10 // Using if as an expression val result = if (number > 5) "Greater than five" else "Five or less" // Using try-catch as an expression val value = try { riskyOperation() } catch (e: Exception) { -1 } println("Result: $result") println("Value: $value") }
In this code, you see two Kotlin idioms in action. First, the if block is used as an expression to assign a value to the variable result. Instead of requiring a ternary operator, the if directly returns either "Greater than five" or "Five or less" based on the condition. Second, the try-catch block is used as an expression to assign a value to value. If riskyOperation() throws an exception, the catch block returns -1, otherwise it returns the result of riskyOperation().
The benefits of using expressions over statements are clear:
- You can assign the result of a condition or error-handling block directly to a variable;
- Your code is more concise and readable, with less boilerplate;
- There is no need for additional constructs like the ternary operator, reducing the number of language features you must remember;
- Error handling and value assignment are combined, making intent clearer.
These idioms help you write safer and more maintainable code by reducing opportunities for errors and making your logic explicit and easy to follow.
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat