Kotlin-是否可以从高阶函数返回变量? [英] Kotlin - Is it possible to return a variable from a higher order function?

查看:61
本文介绍了Kotlin-是否可以从高阶函数返回变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个来自单独库的Kotlin函数,该函数将函数作为参数并从回调中获取我需要的变量:

I have a Kotlin function from a separate library that takes a function as a parameter and gets the variable I need from the callback:

object Session {
    fun get(callback: (accessToken: String?) -> Unit): Boolean {
        SomeOtherClass(callback).get()
        return true
     }
}

然后从另一个类中调用它(在Java中):

Then to call it from another class I make the call (in java):

public String getToken() {
     Session.INSTANCE.get((accessToken) -> {
          // I want the method getToken() to be able to 'return accessToken;' 
          // but this call back returns Unit and the get method itself returns Boolean
     });
}

是否有一种方法可以直接从getToken()返回变量accessToken,或者至少返回等效值? Session.get是异步的,因此创建全局"变量将返回null,因为尚未分配值.这是我尝试过的一件事:

Is there a way to return the variable accessToken from getToken() directly, or at least the equivalent value? Session.get is async so creating a "global" variable returns null because the value hasn't been assigned yet. This is one thing I have tried:

public String getToken() {
     String temp;
     Session.INSTANCE.get((accessToken) -> {
          temp = accessToken;
     });
     return temp;
}

相对于函数式编程而言,这是新事物,因此不胜感激!

Relatively new to functional programming so any help is appreciated!

推荐答案

在不阻塞进行调用的线程的情况下,无法从调用该方法的方法返回回调的最终结果.存在回调的原因是,这样您就不会阻塞进行调用的线程.在Android上,如果您阻塞主线程几秒钟,您的应用将崩溃,并显示应用无响应"消息.

You can't return a callback's eventual result from the method that calls it without blocking the thread that made the call. The reason callbacks exist is so you won't block the thread that's making the call. On Android, your app will crash with an Application Not Responding message if you block the main thread for a few seconds.

如果使用Kotlin,则可以使用suspendCancellableCoroutine包装库回调,以使它们与协程兼容.协程暂停函数确实允许您返回延迟的结果.

If you use Kotlin, you can wrap library callbacks using suspendCancellableCoroutine to make them coroutine-compatible. Coroutine suspend functions do allow you to return delayed results.

这篇关于Kotlin-是否可以从高阶函数返回变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆