How to inject dependencies through Scala Reader from Java code

北城以北 提交于 2019-12-12 16:16:56

问题


Here is a dependency service:

  public class Service1 {}

Scala code that uses it via reader:

object TupleEx {
  type FailFast[A] = Either[List[String], A]
  type Env[A] = ReaderT[FailFast, Service1, A]

  import cats.syntax.applicative._
  import cats.instances.either._

  def f:Env[Int] = 10.pure[Env]
}

Java test where I try to inject Service1:

  @Test
  public void testf() {
    Service1 s = new Service1();
    TupleEx.f().run(s);
  }

I am getting an exception:

Error:(10, 16) java: method run in class cats.data.Kleisli cannot be applied to given types; required: no arguments found: com.savdev.Service1 reason: actual and formal argument lists differ in length

Although in Scala I would be able to run it as:

TupleEx.f().run(s);

回答1:


Try:

TupleEx.f().run().apply(s);
  • run() is the "getter" method of the val inside Kleisli
  • apply() is what is usually hidden by Scala's syntactic sugar

General advice:

  1. Write down an interface in Java
  2. Implement the interface in Scala
  3. Use whatever you've written only through Java interfaces when writing code in Java.
  4. Do not attempt to use Scala interfaces directly when writing code in Java.

Remember: Scala compiler understands Java. Java does not know anything about Scala. Implementing Java interfaces in Scala is trivial. Using Scala interfaces from Java is awkward.



来源:https://stackoverflow.com/questions/55382975/how-to-inject-dependencies-through-scala-reader-from-java-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!