InterviewSolution
| 1. |
Explain about the “when” keyword in the context of Kotlin. |
|
Answer» The “when” keyword is used in Kotlin to substitute the switch operator in other languages such as Java. When a certain condition is met, a specific BLOCK of code must be run. Inside the when expression, it compares all of the branches one by one until a match is discovered. After finding the first match, it proceeds to the conclusion of the when block and executes the code immediately following the when block. We do not need a break STATEMENT at the end of each CASE, unlike switch cases in Java or any other programming language. For example, // KOTLINfun main(args: Array<String>) { var temp = "Interview" when(temp) { "Interview" -> println("Interview Bit is the solution.") "Job" -> println("Interview is the solution.") "SUCCESS" -> println("Hard Work is the solution.") }}Output:- Interview Bit is the solution.Explanation:- In the above code, the variable temp has the VALUE “Interview”. The when condition matches for the exact value as that of temp’s and executes the corresponding code statements. Thus, “Interview Bit is the solution” is printed. |
|