Junior — Middle
Can you describe the concept of side effects in programming and give examples?
sobes.tech AI
Answer from AI
Side effects in programming are any changes in state that occur outside the local scope of a function or method, or interactions with the external world, beyond returning a value. These include, for example, changing global variables, writing to a file, modifying a database, outputting to the screen, sending network requests.
Example:
var counter = 0
fun increment() {
counter += 1 // changing external state — side effect
}
fun sum(a: Int, b: Int): Int {
return a + b // no side effects, pure function
}
In Android, side effects are often related to updating the UI, saving data, or calling APIs. Managing side effects is important for code predictability and testability.