scala - 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宏会有帮助吗?
解决方案
如果同步 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 { ... }
.
推荐阅读
- excel - 列出文件夹中的文件 excel onedrive
- firebase-authentication - Google / DialogFlow 上的操作:从没有转换对象的 idToken 获取用户数据
- firebase - Firebase 好友列表关系
- jquery - jquery对图像没有响应的爆炸效果
- javascript - 为什么当我通过 fetch API 请求记录我的 React 状态 setState 时会收到两个响应?
- java - 有没有办法使用 Apache Commons Digester 从 xml 中添加 Arraylist 中键的所有值?
- ios - 图像不是从一个 VC 到另一个 VC
- matlab - 如何在 matlab 或 simulink 中对组合(电气和机械)系统执行鲁棒控制
- python - Python 单元测试 - 运行时的模拟补丁?
- aws-lambda - 带有 API Gateway 的 AWS Lambda 返回 500 错误并带有 hello-world 蓝图