Home > Software engineering >  How to change Function0 to the type I want?
How to change Function0 to the type I want?

Time:09-02

I want to make this block of code to be the type of Supplier, people says using () => { ... } to define a Function0[T] which can be automatically transformed to a Java Supplier, but after I add it below I still got error, can anyone help with this?

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()
}
 

edit: withRety and Decorators.ofSupplier is a function in io.github.resilience4j.decorators;

and scala version is 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;
        }

CodePudding user response:

You can use the asJava method of FunctionConverters in Scala 2.13 to convert Function0 to Supplier:

  import scala.jdk.FunctionConverters._

  val scalaFunc0 = { () => "abc" }
  val javaSupplier: java.util.function.Supplier[String] = scalaFunc0.asJava

CodePudding user response:

Ok, I see. I'm using Scala 2.13.8, and by adding that dependency, your code works by default, except I can't find getDefaultRetryInstance, but that's a different story. The idea is that () => { ... } is syntactic sugar for Function0[T] which is automatically converted into a Java Supplier[T]. For example, this works without additional imports, except for importing Supplier:

  val mySup: Supplier[String] = () => {
    "done"
  }
  println(mySup.get()) // done

So if you can update your Scala version, this should go away on its own. If not, then you probably have to make this conversion explicit. You can wrap the function () => { ... } inside asJavaSupplier, similar to this:

  protected def helper(): Unit = {
    Decorators
      .ofSupplier {
        asJavaSupplier { () =>
          {
            determinationService.callService() match {
              case Success(getTaxResponse) => // ...
              case Failure(exception)      => // ...
            }
          }
        }
      }
      .withRetry(getTaxResilience)
      .get()
  }

You'll find the right path from which to import it in the docs. I put the docs for your Scala version in the link. On Scala 2.13 it changes paths so it makes no sense to show you from where I imported it.

  • Related