简体   繁体   English

如何从 java class 访问 kotlin 代码

[英]how to access kotlin code from java class

Hi I have a kotlin use case which I want to call from java code how can I do that.嗨,我有一个 kotlin 用例,我想从 java 代码中调用它,我该怎么做。 this is what I have tried这是我尝试过的

this is my use case这是我的用例

@PerApp
class OnStandUseCase @Inject constructor(
    private val orderRepository: OrderRepository,
    private val serviceOrderTypeProvider: ServiceOrderTypeProvider
) : UseCaseCoroutine<GenericResponse, OnStandUseCase.Params>() {

    override suspend fun run(params: Params) = orderRepository.notifyOnStand(
        serviceOrderTypeProvider.apiPathFor(params.serviceType),
        params.id,
        params.action
    )

    data class Params(val serviceType: String, val id: String, val action: TimestampedAction)
}

UseCaseCoroutine用例协程

abstract class UseCaseCoroutine<out Type, in Params> where Type : Any {

    abstract suspend fun run(params: Params): Type

    operator fun invoke(params: Params, onResult: (type: Type) -> Unit = {}) {
        val job = GlobalScope.async(Dispatchers.IO) { run(params) }
        GlobalScope.launch(Dispatchers.Main) { onResult(job.await()) }
    }
}

This is how I call it from my kotlin class这就是我从 kotlin class 中调用它的方式

  try {
            onStandUseCase(OnStandUseCase.Params(serviceType, id, action)) {
                callback.invoke(it)
            }
        } catch (exception: Exception) {
            onStandResponseErrors()
        }

But what is the equivalant to call from java class但是从 java class 调用的等价物是什么

this is what I tried这是我试过的

 onStandUseCase.run(new OnStandUseCase.Params("abcd", "1", new TimestampedAction("1","2"))){
            
        }

I get an error Expected 2 arguments but found only one我收到一个错误Expected 2 arguments but found only one

Not exactly sure what is the right way to call the use case from java code不完全确定从 java 代码调用用例的正确方法是什么

any suggestions please请有任何建议

thanks R谢谢 R

You cannot call suspend functions from Java.您不能从 Java 调用suspend函数。 (You technically could, but doing it correctly would be extremely difficult, and I strongly recommend you just avoid even trying.) (从技术上讲你可以,但正确地做到这一点非常困难,我强烈建议你不要尝试。)

In your Kotlin code, write a function that is not a suspend function that converts it to an appropriate Java idiom -- an RxJava result, or a future. In your Kotlin code, write a function that is not a suspend function that converts it to an appropriate Java idiom -- an RxJava result, or a future. Call that method from Java instead.而是从 Java 调用方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM