[英]How to write parametric/generic functions in kotlin
我正在嘗試找到一種解決方法,使Spring Reactive Webclient
與JDBC
工作。 這是我的想法: 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.