编写我自己的语法糖函数来使用 Await.result [英] Writing my own syntatic sugar function to work with Await.result

查看:45
本文介绍了编写我自己的语法糖函数来使用 Await.result的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能改变这个:

Await.result(purchase, 5 seconds)

能够以如下方式编写相同的语句:

To be able to write the same statement in the following way:

purchase.await(5 seconds)

只是想通过编写我自己的自定义 dsl 来学习如何重写我的一些代码.

Just trying to learn how to rewrite some of my code by writing my own custom dsl.

推荐答案

您可以创建自己的隐式类:

import scala.concurrent.{Await, Awaitable}
import scala.concurrent.duration.Duration

object syntax {
  object await {
    implicit class AwaitableOps[T](private val awaitable: Awaitable[T]) extends AnyVal {
      @inline
      final def await(atMost: Duration): T =
        Await.result(awaitable, atMost)
    }
  }
}

你可以这样使用:

import syntax.await._
purchase.await(5.seconds) // Note the dot. The postFix operator syntax is discouraged.

这篇关于编写我自己的语法糖函数来使用 Await.result的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆