title: Returning value from Scala future completion
body: <p>Coming from a Java background, I have been trying to teach myself Scala for some time now. As part of that, I am doing a small pet project that exposes a HTTP endpoint that saves the <code>registration number</code>of a vehicle against the <code>owner</code> and returns the status.</p>
  
  <p>To give more context, I am using <a href="http://slick.lightbend.com/" rel="nofollow">Slick</a> as FRM which performs DB operations asynchronously and returns a <code>Future</code>.
  Based on the output of this Future, I want to set the <code>status</code> variable to return back to the client.</p>
  
  <p>Here, is the code</p>
  
  <pre><code>def addVehicleOwner(vehicle: Vehicle): String = {
      var status = ""
      val addFuture = db.run((vehicles returning vehicles.map(_.id)) += vehicle)
      addFuture onComplete {
        case Success(id) =&gt; {
          BotLogger.info(LOGTAG, s"Vehicle registered at $id ")
          status = String.format("Registration number - '%s' mapped to owner '%s' successfully", vehicle.registration,
            vehicle.owner)
          println(s"status inside success $status") //--------- (1)
        }
        case Failure(e: SQLException) if e.getMessage.contains("SQLITE_CONSTRAINT") =&gt; {
          status = updateVehicleOwner(vehicle)
          BotLogger.info(LOGTAG, s"Updated owner='${vehicle.owner}' for '${vehicle.registration}'")
        }
        case Failure(e) =&gt; {
          BotLogger.error(LOGTAG, e)
          status = "Sorry, unable to add now!"
        }
      }
      exec(addFuture)
      println(s"Status=$status") //--------- (2)
      status
    }
  
    // Helper method for running a query in this example file:
    def exec[T](sqlFuture: Future[T]):T = Await.result(sqlFuture, 1 seconds)
  </code></pre>
  
  <p>This was fairly simple in Java. With Scala, I am facing the following problems:</p>
  
  <ul>
  <li>The expected value gets printed at (1), but (2) always prints empty string and same is what method returns. Can someone explain why?</li>
  <li><p>I even tried marking the <code>var status</code> as <code>@volatile var status</code>, it still evaluates to empty string.</p></li>
  <li><p>I know, that the above is not the functional way of doing things as I am muting state. What is the clean way of writing code for such cases.</p></li>
  <li>Almost all the examples I could find described how to map the result of <code>Success</code> or handle <code>Failure</code> by doing a <code>println</code>. I want to do more than that.</li>
  <li>What are some good references of small projects that I can refer to? Specially, that follow TDD.</li>
  </ul>