Câu hỏi phỏng vấn Kotlin
Câu hỏi

Explain advantages of when vs switch in Kotlin

Câu trả lời

Here are the key advantages of using when instead of switch in Kotlin:

  1. when can be used as an expression or statement, while switch is just a statement. This means when can return a value, making it more flexible[1].

  2. when has a more concise syntax compared to switch. It uses -> instead of case and break, and multiple conditions can be grouped with commas[1][3].

  3. An else branch is required for when expressions to ensure a value is always returned, making the code safer. switch relies on a default case which is optional[1][4].

  4. when can have arbitrary conditions, not just equality checks like switch. This includes ranges, object types, and boolean expressions[1][3].

  5. when can be used without an argument, checking each branch condition directly. switch requires an expression to switch on[1].

  6. **when bra...

middle

middle

Gợi ý câu hỏi phỏng vấn

senior

Explain the difference between Inline classes vs type aliases

senior

What is Kotlin backing field is used for?

middle

What is the difference between suspending vs. blocking?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào