代码之家  ›  专栏  ›  技术社区  ›  Eric Kolotyluk

Scala中是否有一种优雅的方式来定义基于同步API的异步API?

  •  1
  • Eric Kolotyluk  · 技术社区  · 7 年前

    我怀疑答案是否定的,但我想我还是会问。

    考虑到

    trait foo {
      def sum(a: Int, b: Int): Int
    }
    

    是否有一些Scala魔术我可以做生产,或隐式定义

    trait fooAsync {
      def sum(a: Int, b: Int): Future[Int]
    }
    

    还是我必须强制它,并显式定义fooancy?Scala宏会有帮助吗?

    1 回复  |  直到 7 年前
        1
  •  4
  •   Aki    7 年前

    如果同步api由您定义,则可以编写以下内容:

    trait Foo {
      type Response[A]
    
      def sum(a: Int, b: Int): Response[Int]
      def diff(a: Int, b: Int): Response[Int]
      /* ... */
    }
    
    trait SyncFoo extends Foo {
      type Response[A] = A
    }
    
    trait AsyncFoo extends Foo {
      type Response[A] = Future[A]
    }
    

    如果您真的不需要异步接口,那么您可以将对同步api的所有调用封装在 Future { ... } .