title: Make asynchronous call synchronous in Kotlin
body: <p>I have an API I have no control over.... which contains a method that does some work and returns the results asynchronously. I would like to call this method synchronously in parts of my application. I have done this by adding a class <code>ResultHandler</code> which captures and returns the result. Is there a better way of doing this than the way I've done it below? Perhaps using standard kotlin (or Java as last resort) library methods. My preference would be for  <code>awaitReply</code> to return the result and also to remove the <code>CountdownLatch</code>.</p>
  
  <pre><code>class Main {
      companion object {
          @JvmStatic
  
          fun main(args: Array&lt;String&gt;) {
              val result1 = Main().nonAsyncMethod1(arrayListOf(1, 2, 3, 4, 5))
              result1.elements.forEach { println(it) }
          }
      }
  
      class Result1(var elements: Collection&lt;String&gt;)
  
      fun asyncMethod1(x: Collection&lt;Int&gt;, callback: (Result1) -&gt; Unit) {
          Thread().run {
              // do some calculation
              Thread.sleep(1000)
              callback(Result1(x.map { "\"$it\"" }.toList()))
          }
      }
  
      private fun nonAsyncMethod1(entities: Collection&lt;Int&gt;): Result1 {
          val resultHandler = ResultHandler&lt;Result1&gt;()
  
          awaitReply&lt;Result1&gt; {
              asyncMethod1(entities, resultHandler)
          }
          return resultHandler.getResponse()
      }
  
      open class ResultHandler&lt;T : Any&gt; : (T) -&gt; Unit {
          private lateinit var response: T
          private val latch = CountDownLatch(1)
  
          override fun invoke(response: T) {
              latch.countDown()
              this.response = response
          }
  
          fun getResponse(): T {
              latch.await()
              return response
          }
      }
  
      private fun &lt;T : Any&gt; awaitReply(call: () -&gt; Unit) {
          return call.invoke()
      }
  }
  </code></pre>