kotlin - 如何在 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 expected
并Mono.fromCallable(callable).subscribeOn(Schedulers.parallel()).publishOn(jdbcScheduler)
返回编译错误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,但我让它们尽可能靠近您的代码。
推荐阅读
- python - ValueError:未知标签类型:RandomForestClassifier 中的“未知”
- swift - 为什么有必要从 Optional 强制转换为 Any?
- yii2 - 如何在yii2中将params文件转换为i18n
- ispconfig - ISPConfig 自动配置 IP 地址
- python - 如何在 Python 中使用 Selenium 成功获取嵌套在 span 标签下的所有图像 src
- 3d - LIBGDX 3D:无法准确确定相机光线击中哪个网格三角形
- java - Java 递增编号
- c++ - 是否存在具有对数时间插入、删除和查找(带距离)的排序数据结构?
- android - UnhandledPromiseRejectionWarning: CordovaError: No emulator images (avds) found
- java - 如何使用 java opencv 检测图像特征?