Writing my own syntatic sugar function to work with Await.result

别等时光非礼了梦想. 提交于 2021-01-27 21:08:11

问题


How could I transform this:

Await.result(purchase, 5 seconds)

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

purchase.await(5 seconds)

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


回答1:


You can create your own implicit class:

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)
    }
  }
}

Which you can use like this:

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



回答2:


In Scala 3 you might write extension method like so

def [T](f: Future[T]).await(atMost: Duration) = Await.result(f, atMost)

scastie example



来源:https://stackoverflow.com/questions/60456103/writing-my-own-syntatic-sugar-function-to-work-with-await-result

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!