首页 > 解决方案 > Scala 中是否有一种优雅的方式来定义基于同步 API 的异步 API?

问题描述

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

鉴于类似

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

我可以做一些 Scala 魔法来产生或隐式定义吗

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

还是我只需要暴力破解它,并明确定义 fooAsync ?Scala宏会有帮助吗?

标签: scalascala-macros

解决方案


如果同步 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 { ... }.


推荐阅读