Junior — Middle
What methods can be used to save and use a reference to a function in code?
sobes.tech AI
Answer from AI
In Android, there are several approaches to save and use a reference to a function:
-
Callback interfaces
- Create an interface with a method, implemented in the desired class.
- Pass an object of the interface, call the method when needed.
-
Lambda expressions and functional interfaces (Java 8+ / Kotlin)
- In Kotlin, functions are first-class objects, so you can pass and store references directly.
- In Java, you can use functional interfaces and lambdas.
-
Method references
- In Java 8+, you can use method references, e.g.,
ClassName::methodName.
- In Java 8+, you can use method references, e.g.,
-
Using
Runnable,Callable, or other standard interfaces- For simple cases, you can store objects of these interfaces.
Example in Kotlin:
fun performOperation(operation: () -> Unit) {
operation()
}
fun main() {
val sayHello = { println("Hello") }
performOperation(sayHello) // Passing a function reference
}
Thus, function references can be stored in variables, passed as parameters, and invoked later.