Sobes.tech
Junior — Middle

Is it recommended to pass context as a parameter to a function, and why?

sobes.tech AI

Answer from AI

In Android, it is recommended to pass a Context object as a parameter to a function when the function needs access to application resources, system services, or to create UI components. Context provides information about the current state of the application and allows access to things like:

  • access to resources (strings, images);
  • launching activities or services;
  • obtaining system services (e.g., LayoutInflater, NotificationManager);
  • access to files and databases.

Passing Context makes functions more versatile and independent of specific classes, and also facilitates testing.

Example:

fun showToast(context: Context, message: String) {
    Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
}