Scala 中是否有一种优雅的方式来定义基于同步的异步 API?
Is there an elegant way in Scala to define an asynchronous API based on a synchronous one?
我怀疑答案是否定的,但我想我还是会问的。
给出类似的东西
trait foo {
def sum(a: Int, b: Int): Int
}
我可以做一些 Scala 魔术来生成或隐式定义
trait fooAsync {
def sum(a: Int, b: Int): Future[Int]
}
或者我只需要强制执行它,并明确定义 fooAsync 吗? Scala 宏有帮助吗?
如果同步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 { ... }
.
中
我怀疑答案是否定的,但我想我还是会问的。
给出类似的东西
trait foo {
def sum(a: Int, b: Int): Int
}
我可以做一些 Scala 魔术来生成或隐式定义
trait fooAsync {
def sum(a: Int, b: Int): Future[Int]
}
或者我只需要强制执行它,并明确定义 fooAsync 吗? Scala 宏有帮助吗?
如果同步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 { ... }
.