Junior — Middle
What methods can be used to implement branching logic in programming code?
sobes.tech AI
Answer from AI
To implement branching logic in Android (Java/Kotlin) code, several methods can be used:
-
Conditional operators (
if-else,whenin Kotlin): the simplest way to choose a branch of execution. -
switchoperator (Java) orwhen(Kotlin): convenient when there are many options. -
Polymorphism: creating class hierarchies with overridden methods, allowing logic selection through objects.
-
Strategy (design pattern): encapsulating different algorithms into separate classes and selecting the appropriate one at runtime.
-
Functional approaches: using lambdas and higher-order functions to pass logic.
Example with when in Kotlin:
fun process(input: Int) {
when (input) {
1 -> println("Branch 1")
2 -> println("Branch 2")
else -> println("Other branch")
}
}
This approach makes it easy to extend and maintain branching logic.