问题
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