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

Viewed 44

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.

2 Answers

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.
Related