簡體   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