首页 > 解决方案 > 如何在 kotlin 中编写参数/泛型函数

问题描述

我正在尝试找到一种解决方法来Spring Reactive Webclient使用JDBC. 这是我的想法:https ://gitorko.github.io/2019/04/02/Spring-Webflux-Reactive-JDBC/ 。

我正在编写一个service调用 jdbc 存储库接口的方法,而不是返回我的域对象的类型,而是MyClass返回Mono<MyClass>如下:

//other specific imports here
import org.springframework.stereotype.Service
import reactor.core.publisher.Mono
import reactor.core.scheduler.Scheduler
import reactor.core.scheduler.Schedulers
import java.util.concurrent.Callable

@Service
class MyClassService(val repo: MyClassRepository, val jdbcScheduler: Scheduler){

    fun save(obj: MyClass?): Mono<MyClass?>? {
       return asyncCallable { repo.save(obj) }
    }

    protected fun <S> asyncCallable(callable: Callable<S>?): Mono<S>? {
        return Mono.fromCallable(callable).subscribeOn(Schedulers.parallel()).publishOn(jdbcScheduler)
    }
}

//this is a jdbc repository
interface MyClassRepository : CrudRepository<MyClass, UUID> {}

现在的问题是调用asyncCallable { repo.save(obj) }返回编译错误inferred type is MyClass? but TypeVariable(S) was expectedMono.fromCallable(callable).subscribeOn(Schedulers.parallel()).publishOn(jdbcScheduler)返回编译错误inferred type is Callable<S>? but Callable<out TypeVariable(T)!> was expected。通过阅读有关 kotlin 泛型的信息,我了解到这与方差有关。如果我没记错的话,函数asyncCallable在泛型类型上是不变的S,在这种情况下需要协方差吗?

标签: kotlingenericstypesspring-webfluxhigher-order-functions

解决方案


我认为您需要的语法是asyncCallable(Callable { repo.save(obj) }).

完整示例:

@Service
class MyClassService(val repo: MyClassRepository, val jdbcScheduler: Scheduler){

    fun save(obj: MyClass): Mono<MyClass?>? {
        return asyncCallable(Callable { repo.save(obj) })
    }

    protected fun <S> asyncCallable(callable: Callable<S>): Mono<S>? {
        return Mono.fromCallable(callable).subscribeOn(Schedulers.parallel()).publishOn(jdbcScheduler)
    }
}

我也会删除?s,但我让它们尽可能靠近您的代码。


推荐阅读