Scala中有一种优雅的方法来定义基于同步API的异步API吗?

时间:2018-12-11 20:38:13

标签: scala scala-macros

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

给出类似的

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

我可以制作或隐式定义Scala魔术吗

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

还是只需要强行使用它,并显式定义fooAsync? Scala宏有帮助吗?

1 个答案:

答案 0 :(得分:4)

如果您定义了同步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 { ... }中。