這個問題已經存在: 如何在 Scala 中使用 Resilience4J 3天前關閉。
我想讓這個代碼塊成為供應商的型別,人們說使用 () => { ... } 來定義一個可以自動轉換為 Java 供應商的 Function0[T],但是在我在下面添加它之后我仍然有錯誤,有人可以幫忙嗎?
protectet def helper() {
Decorators.ofSupplier { () => {
determinationService.callService() match {
case Success(getTaxResponse) =>
case Failure(exception) =>
}
}
//got error: type mismatch required: Supplier[T_], found: Function0[Unit]
}.withRetry(getTaxResilience.getDefaultRetryInstance())
.get()
}
編輯:withRety 和 Decorators.ofSupplier 是 io.github.resilience4j.decorators 中的一個函式;
和 scala 版本是 2.12.14
static <T> Decorators.DecorateSupplier<T> ofSupplier(Supplier<T> supplier) {
return new Decorators.DecorateSupplier(supplier);
}
public Decorators.DecorateSupplier<T> withRetry(Retry retryContext) {
this.supplier = Retry.decorateSupplier(retryContext, this.supplier);
return this;
}
uj5u.com熱心網友回復:
您可以使用 Scala 2.13 中的asJava方法FunctionConverters轉換Function0為Supplier:
import scala.jdk.FunctionConverters._
val scalaFunc0 = { () => "abc" }
val javaSupplier: java.util.function.Supplier[String] = scalaFunc0.asJava
uj5u.com熱心網友回復:
好的我明白了。我正在使用 Scala 2.13.8,并且通過添加該依賴項,您的代碼默認作業,除了我找不到getDefaultRetryInstance,但這是一個不同的故事。這個想法是() => { ... }一種語法糖,Function0[T]它會自動轉換為 Java Supplier[T]。例如,這無需額外的匯入即可作業,除了匯入Supplier:
val mySup: Supplier[String] = () => {
"done"
}
println(mySup.get()) // done
因此,如果您可以更新您的 Scala 版本,這應該會自行消失。如果不是,那么您可能必須明確地進行此轉換。您可以將函式包裝在() => { ... }內asJavaSupplier,類似于:
protected def helper(): Unit = {
Decorators
.ofSupplier {
asJavaSupplier { () =>
{
determinationService.callService() match {
case Success(getTaxResponse) => // ...
case Failure(exception) => // ...
}
}
}
}
.withRetry(getTaxResilience)
.get()
}
您將在檔案中找到匯入它的正確路徑。我將您的 Scala 版本的檔案放在鏈接中。在 Scala 2.13 上,它被移到了不同??的路徑,因此向您展示我從哪里匯入它是沒有意義的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/504780.html
標籤:斯卡拉
