Примеры методов обратного вызова (callbacks)
Callback в чистом виде, это когда вы сформировали задачу и отправили её выполнять какому то там процессу, но не ждёте её завершения и продолжаете работать, а чтобы к вам мог вернутся результат работы, вы для воркера передаёте ссылку на свой класс с кастом в интерфейс калбека в котором обьявлен метод, при помощи которого воркер может вернуть данные. Вся работа происходит асинхронно без блокировок и ожиданий. В этом смысл калбеков, так как некоторые задачи могут идти долго, а некоторые быстро, но каллер не должен об этом заботиться, он просто предоставляет интерфейс для ответа и продолжает работу.
import java.util.ArrayList; import java.util.Random; /** * * @author mutagen */ public class CallBackDemo < public static void main(String[] args) < Caller caller = new Caller(); for (int i = 0; i < 10; i++) < new Worker(caller).start(); >// итого у нас 9 воркеров отработали и вернули ответ по калбеку в коллекцию System.out.println(caller.getStatuses()); > static class Caller implements Callback < private ArrayListstatuses = new ArrayList<>(); public ArrayList getStatuses() < return statuses; >@Override public void callMeBack(int status) < // тут может быть логика куда вернутся данные, может быть коллекция, я выбрал попроще synchronized (statuses) < statuses.add(status); >> > static interface Callback < // подготовим интерфейс по которому нам будут возвращать данные void callMeBack(int status); >static class Worker extends Thread < private Callback cb; public Worker(Callback cb) < this.cb = cb; >int pleaseDoMeAFavor() < return new Random().nextInt(); >@Override public void run() < // выполним работу int st = pleaseDoMeAFavor(); // и вернём данные вызывающему по калбек интерфейсу cb.callMeBack(st); >> >
Допустим, мы разрабатываем фреймворк. У нас есть определенный шаблон действий, в котором только один пункт мы не можем прописать жестко и в этом месте необходимо, чтобы пользователь вставил свой функционал. Это можно сделать абстрактным методом, но в этом случае проблема: во-первых мы не сможем динамически менять такие “вставки”, во-вторых, для 1000 функционалов мы получим огромную иерархию наследования. Кроме того, так как множественное наследование в Java не поддерживается, наследование можно использовать только в отдельных случаях. В этом случае можно использовать коллбэки.
Яркий пример использования колбэков – Spring-овские темплейты для работы с JDBC – они исполняют общие функции самостоятельно, передавая пользователю только такие операции, как обработка ResultSet-ов.
У нас есть темплейтный класс:
package callbacks; import java.util.Arrays; import java.util.List; public class Template < private ICustomOperation callback; public Template(ICustomOperation callback) < this.callback = callback; >public void setCallback(ICustomOperation callback) < this.callback = callback; >public void processData(List lines) < for (String line : lines) < System.out.println("Input: " + line); line = "[" + line + "]"; System.out.println("Standart operation 1 result : " + line); line = line.replaceAll(" ", "_"); System.out.println("Standart operation 2 result : " + line); line = callback.evaluate(line); // здесь мы будем передавать контроль над обработкой пользователю System.out.println("Custom operation result : " + line); line = line.toLowerCase(); System.out.println("Standart operation 3 result : " + line); >> >
package callbacks; public interface ICustomOperation
И различные его реализации:
package callbacks; public class CustomOperation implements ICustomOperation < public String evaluate(String input) < return "CUSTOM: " + input; >>
package callbacks; public class AnotherCustomOperation implements ICustomOperation < public String evaluate(String input) < return "ANOTHER CUSTOM: " + input; >>
Template template = new Template(new CustomOperation()); List data = Arrays.asList(new String[] < "first line", "SEcOnD LiNe" >); template.processData(data); template.setCallback(new AnotherCustomOperation()); template.processData(data);
Есть ещё одно применение: допустим, у нас есть объект, у которого private метод, который вы не хотите делать public или protected. Вы вызваете метод другого класса и изнутри него хотите сделать вызов нашего private-метода.Это можно сделать следующим образом:
package callbacks;
package callbacks; public class PrivateFieldHolder < private OuterCaller outerCaller; public OuterCaller getOuterCaller() < return outerCaller; >public void setOuterCaller(OuterCaller outerCaller) < this.outerCaller = outerCaller; >public void publicMethod() < System.out.println("Holder: public method call"); // здесь хитрая штука: мы передаем в вызов метода // внешнего класса коллбэк, который // является анонимным классом внутри данного класса // т.к. этот анонимный класс видит private-метод, то мы // можем поместить внутрь callPrivateMethod вызов этого // private-метода. Таким образом при вызове // callPrivateMethod во внешнем классе позволит обратиться // к private-методу этого класса. outerCaller.callFromOutsidePrivateMethod(new IPrivateMethodCallback() < public void callPrivateMethod(String caller) < privateMethod(caller); >>); > private void privateMethod(String caller) < System.out.println(caller + ": private method call"); >>
package callbacks; public interface IPrivateMethodCallback
Внешний класс, которому нужно вызвать private-метод:
package callbacks; public class OuterCaller < public void callFromOutsidePrivateMethod(IPrivateMethodCallback callback) < System.out.println("Outer method call"); callback.callPrivateMethod("Outer caller"); >>
PrivateFieldHolder pfh = new PrivateFieldHolder(); OuterCaller oc = new OuterCaller(); pfh.setOuterCaller(oc); pfh.publicMethod();
Вам також може сподобатися
![]()
Уроки по основам Java 22 84 913
Список уроков Следующий урок>> Hello, World! Добро пожаловать на курс основ программирования на

Архитектура андроид-приложений 1 3 393
Доклад Алексея Быкова из Лаборатории Касперского на Android Academy, где он понятно на примерах

Уроки по android разработке на Java 0 115
Вернуться к уроку 9 Перейти к уроку 10 [mlw_quizmaster quiz=9]
![]()
Уроки по основам Java 24 17 781
<<Предыдущий урок Список уроков Следующий урок>> Объекты Почти весь код, написанный на языке

Инструменты android разработчика 4 21 505
Это очередное видео из серии “Инструменты андроид-разработчика”, в котором мы начинаем разбираться с таким

Документация по android 3 8 223
Перевод документации официального сайта developer.android.com RelativeLayout – это view group, которая располагает на экране
Kotlin callback functions with code examples
In Kotlin programming, a callback function is a function that is passed as an argument to another function. The receiving function then invokes the callback function at an appropriate time during its execution. This enables the receiving function to execute the callback function asynchronously, providing a way for the caller to handle the result of the function execution.
Callback functions are an essential component of asynchronous programming in Kotlin. Asynchronous programming is a programming paradigm where the execution of a program is divided into multiple threads of execution. These threads can run independently of each other and communicate through shared data structures or events. Asynchronous programming is commonly used to handle time-consuming tasks that would otherwise block the main thread of execution, such as network requests or file I/O operations.
Callback functions are also commonly used for event handling. An event is an occurrence in a program that is triggered by some external action, such as user input or a timer. Callback functions can be used to handle these events, allowing the program to respond to user input or other external stimuli in real-time.
Defining Callback Functions in Kotlin
In Kotlin, callback functions are defined as lambda expressions. A lambda expression is a small piece of code that can be executed independently of the main program. A lambda expression is defined using the following syntax:
< argumentList ->codeBody >
The argumentList is a list of parameters that the lambda expression takes, and the codeBody is the code that the lambda expression executes. The -> operator separates the argument list from the code body.
For example, let’s define a lambda expression that takes two integer arguments and returns their sum:
val sum = < x: Int, y: Int ->x + y >
In this example, the sum lambda expression takes two integer arguments x and y and returns their sum. We can invoke this lambda expression by passing it as an argument to another function:
fun printResult(x: Int, y: Int, sum: (Int, Int) -> Int) val result = sum(x, y)
println("The sum of $x and $y is $result")
>
printResult(2, 3, sum)
In this example, the printResult function takes three arguments: two integers x and y , and a lambda expression sum that takes two integer arguments and returns their sum. The printResult function calculates the sum of x and y by invoking the sum lambda expression and then prints the result to the console.
Using Callback Functions in Kotlin
Callback functions are commonly used in Kotlin programming to handle asynchronous tasks and events. Let’s consider an example where we want to load some data from a remote server asynchronously using a callback function.
fun loadDataFromServer(callback: (List) -> Unit) // Simulate loading data from a remote server
Thread.sleep(5000)
// Return some dummy data
val data = listOf("John", "Jane", "Bob", "Alice")
// Invoke the callback function with the loaded data
callback(data)
>
In this example, the loadDataFromServer function takes a callback function as an argument. The callback function takes a list of strings as its argument and returns nothing. Inside the loadDataFromServer function, we simulate loading data from a remote server by sleeping the thread for five seconds. Then, we create a dummy list of names and invoke the callback function with the loaded data.
Now, let’s invoke the loadDataFromServer function and handle the loaded data using a callback function:
fun main() loadDataFromServer < data ->
println("Loaded data: $data")
>
println("Loading data. ")
>
In this example, we invoke the loadDataFromServer function and pass a lambda expression as the callback function. The lambda expression takes a list of strings as its argument and prints the loaded data to the console.
When we run this program, we see that the Loading data. the message is printed first, followed by the Loaded data: [John, Jane, Bob, Alice] message after five seconds.
Conclusion
In this article, we have explored the concept of Kotlin callback functions and how they are used in Kotlin programming. We have seen that callback functions are essential for handling asynchronous tasks and events in Kotlin, and they are defined using lambda expressions. We have also provided examples of how callback functions are used in practice, including loading data from a remote server asynchronously.
Callback functions are a powerful and versatile feature of Kotlin programming, and they enable developers to write efficient and scalable programs. By mastering the use of callback functions, developers can write code that is both concise and expressive, while still providing a high level of functionality and performance.
Callback Functions in Kotlin: How to Use Them Effectively

In this article, we’ll explore the subject of callbacks in Kotlin. Callbacks are one of the most useful and valuable tools at your disposal to extend the functionality and flexibility of your code.
First, we’ll go over what callbacks in general are and why they exist. Next, we’ll explore the implementation of callbacks in Kotlin with some simple examples so you can learn the syntax. Then, we’ll talk about what lambdas are and how to make callbacks asynchronous. Finally, we’ll provide some recommendations on where to implement callbacks.
This article is for Kotlin developers. Therefore, we’ll be working under the assumption that you have a basic understanding of Kotlin and Spring Boot.
If you haven’t yet dipped your toes into Kotlin or any technology similar to it, we recommend you spend some time here first.
With that out of the way, let’s move forward.
Preparing the Groundwork
Now, before we jump into the subject of callbacks, we want to make sure we’re all on the same page. We’ll be crafting our demo site in Spring Boot very quickly using the start.spring.io site.
Do you already know how to do this and just want to read the theory? In that case, you can skip this section.
Setup
If you’re new to Java, all you’ll need in your system is a Java Development Kit installed—either Gradle or Maven—and your favorite integrated development environment. In our case, we’ll have VS Code as our IDE and Gradle.
As we mentioned above, to speed up the process, we’ll start by going to https://start.spring.io and setting up our startup project. Before downloading the zip file, remember to select Spring Web as your dependency.
Home Controller
So, once you’ve downloaded what you need, go to the src/main/java/com/example/demo folder. Create a class file called HomeController.kt.
In it, just input the following code.
package com.example.blog import org.springframework.stereotype.Controller import org.springframework.ui.Model import org.springframework.ui.set import org.springframework.web.bind.annotation.GetMapping @Controller class HomeController < @GetMapping("/") fun home(model: Model): String < model["title"] = "Site" return "home" >>
Now, continue to the src/main/resources/templates folder and create header and footer templates.
We’ve chosen the mustache template language for our templates, but you can make them in the language of your preference.
header.mustache
footer.mustache
home.mustache
header>> >
This is a test site.
footer>>
And, there you go! That’s all you need.
You can now run the code with gradle bootRun in the terminal and see your website on localhost:8080.

If you want an extensive explanation of what’s going on behind the scenes, please check out the Kotlin community and this Spring Boot tutorial.
What Is a Callback?
As defined by Wikipedia, «In computer programming, a callback, also known as a ‘call-after’ function, is any reference to executable code that is passed as an argument to other code; that another code is expected to call back (execute) the code at a given time.»
In essence, a callback is a code passed into a method or function as an argument. Then it’s invoked inside the outer function to complete a routine or action.
This mechanism exists to allow the repurposing of code, reducing the need for boilerplate code and duplication.
Additionally, we use callbacks to continue code execution after completing an asynchronous operation. In this specific case, we refer to callbacks as asynchronous.
This structure is very common in webhooks and API services, where we can’t halt the execution while waiting for a server response. Many modern web APIs, such as fetch, provide this kind of functionality on JavaScript.
Callbacks in Kotlin
Now that we understand what callbacks are, let’s see some examples.
Here’s a simple example of a callback.
package com.example.blog import org.springframework.stereotype.Controller import org.springframework.ui.Model import org.springframework.ui.set import org.springframework.web.bind.annotation.GetMapping @Controller class HomeController < @GetMapping("/") fun home(model: Model): String < model["title"] = buildTitle(::getTitle) return "home" >fun buildTitle(callback: (text: String) -> String): String < return callback.invoke("This site belongs to ") >fun getTitle(text: String): String < return text + "Juan" >>
Notice how we added two new functions to the controller. The first function, buildTitle, receives the callback function. The second function, getTitle, provides the value. This first function indicates that it receives a parameter callback. This is a function that accepts a string (text) and returns a string. It’s the primary key of our callback feature. It allows us to indicate what kind of function we’re expecting and what it’ll provide us.
We then invoke the callback function on our buildTitle, providing it with the text that it needs. Finally, the code returns the result to the method home we just called, which assigns it to the model object.
Regarding our getTitle function, its only purpose is to simply add the string «Juan» to whatever string you provided.
As you can see, there’s nothing complicated.
Callback Block
However, what if you don’t want to have that function necessarily defined on the controller class?
Well, you don’t have to. You can define the structure of the getTitle function as a block directly at the invocation of the buildTitle function. Then, all you have to do is indicate the parameter that it will receive and add the code to execute.
package com.example.blog import org.springframework.stereotype.Controller import org.springframework.ui.Model import org.springframework.ui.set import org.springframework.web.bind.annotation.GetMapping @Controller class HomeController < @GetMapping("/") fun home(model: Model): String < model["title"] = buildTitle() < text ->text + "Juan" > return "home" > fun buildTitle(callback: (text: String) -> String): String < return callback.invoke("This site belongs to ") >>
Notice that we removed the return directive in this case because code blocks explicitly return the last line of code.
Now, you might’ve noticed some particular things about the notation used for callbacks in Kotlin. For example, to indicate that a parameter passed to a function is a function, you must prefix it with :: (a double colon). Additionally, to invoke a callback provided as a parameter, you must use its invoke property instead of just invoking it like any other function in the class.
Thankfully, this is where the differences end in terms of the implementation of callbacks in Kotlin. And as you’ll see in the next section, you have plenty of latitude and flexibility with Kotlin.
Lambda
What if you have a simple function that you feel is more appropriate to store in a variable to provide to multiple functions that use the callback?
Well, that’s where lambdas come in handy.
A lambda is simply a code block that usually fits on a single line. It can be stored in a variable and provided to other functions or executed on the fly.
Here’s a simple example of this.
package com.example.blog import org.springframework.stereotype.Controller import org.springframework.ui.Model import org.springframework.ui.set import org.springframework.web.bind.annotation.GetMapping @Controller class HomeController < @GetMapping("/") fun home(model: Model): String < var lmd = < text: String ->text + "Juan" > model["title"] = buildTitle(lmd) return "home" > fun buildTitle(callback: (text: String) -> String): String < return callback.invoke("This site belongs to ") >>
Here, the lmd variable is our lambda and can be provided to the buildTitle function without the double colon :: indicator.
.png)
Asynchronous Callback
We’ve seen how to use callbacks in different ways. But so far, their usability has been quite limited and niche.
One of the main strengths of using callbacks is the ability to more easily determine and control when to execute certain parts of your code. And as we’ve described above, you might run into issues when you need to wait for another process to finish or have a problem with concurrent processes.
This is why you must use callbacks to provide a mechanism of asynchronicity and allow you to execute code later, when a response is received.
Either by using code blocks or lambda, you can specify particular instructions or behaviors to be executed after receiving a server response. This would allow you to, say, refresh a feed or update an input field.
Conclusion
As we’ve seen throughout this article, callbacks are one of the most fundamental and practical features of most modern programming languages. They allow a lot of latitude and versatility within our solutions. Kotlin has done a great deal to provide developers with a robust and versatile implementation of the mechanism that’s easy to learn and intuitive to use.
However, overusing callbacks can lead to code cluttering and hard-to-spot bugs. That’s why we encourage you to rely on Waldo’s sophisticated and reliable testing solutions.
Waldo’s behavioral replay engine can handle your application screens, variations in load time, and other common flakiness issues. And your team gets real-time, reliable insights on your product.
You can get a customized demo or check out the blog. Learn more here.
How I can use callback in Kotlin?
It is CircleShape( it is View in my xml) and listener in my View. I want to implement OnClick in my Activity.
var listener: OnClickListenerInterface? = null mCircleShape.setOnClickListener(View.OnClickListener < if (listener == null) return@OnClickListener listener. onClick() >)
I know , that in Kotlin getters and setters generic automatics, but how I can set listener if it private. It is code from my Activity, but It doesn’t work
CircleShape.listener = object :OnClickListenerInterface < override fun onClick() < ToastUtils.showSuccessMessage(getContext(),"pressed") >>