繁体   English   中英

如何在 kotlin 中编写参数/泛型函数

[英]How to write parametric/generic functions in kotlin

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

我正在编写一个调用 jdbc 存储库接口的service ,而不是返回我的域对象的类型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 expected inferred type is MyClass? but TypeVariable(S) was expected并且Mono.fromCallable(callable).subscribeOn(Schedulers.parallel()).publishOn(jdbcScheduler)返回编译错误inferred type is Callable<S>? but Callable<out TypeVariable(T)!> was expected inferred type is Callable<S>? but Callable<out TypeVariable(T)!> was expected 通过阅读有关 kotlin 泛型的信息,我了解到这与方差有关。 如果我没有错,函数asyncCallable在泛型类型S上是不变的,在这种情况下需要协方差吗?

我认为您需要的语法是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,但我留下了它们以使其尽可能接近您的代码。

暂无
暂无

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

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