How to get out value from Scala Future onComplete/

2019-08-19 02:02发布

问题:

I have a high level structure of my code as follows. This is just an example replicating the high level structure.:-

import scala.concurrent.Future


class FutureReturnsAValue extends PersonAgeModifier {
  def main(args: Array[String]) {

    val jhonObj = Person("Jhon", 25)

    val punishmentResult = addAgeCurse(jhonObj)
    println("The punishment result for Jhonny is " + punishmentResult)

  }

  def addAgeCurse(person: Person): String = {

    val oldAge = person.age
    val futureAge = LongProcessingOpForAge(person)
    futureAge.onSuccess {

      newAge =>

        if (newAge = oldAge + 5) {
          "screw the kiddo, he aged by 5 years" // somehow return this string
        }

        else {
          "lucky chap, the spell did not affect him" // somehow return this string
        }
    }

  }
}

class PersonAgeModifier {

  def LongProcessingOpForAge(person: Person): Future[Int] = {
    Future.successful {
      person.age + 5
    }
  }
}


case class Person
(
  val name: String,
  var age: Int

)

object Person {
  def apply(name: String, age: Int) = new Person(name, age)

}

So my requirement is this:- I need the string from the addAgeCurse() method. Now I know some off you may suggest to pass the future value LongProcessingOpForAge() as such to main() but that is not what I want here.

Questions:

  1. What is the cleanest way to obtain the string and pass it to main(). ( By clean , I mean something which does not involve using wait for x duration as I would like to avoid any manual intervention.)

Thanks

回答1:

Maybe you're asking for:

scala> import concurrent._, ExecutionContext.Implicits._
import concurrent._
import ExecutionContext.Implicits._

scala> def f = Future(42)
f: scala.concurrent.Future[Int]

scala> def g = f.map(_ + 1)
g: scala.concurrent.Future[Int]

scala> :pa
// Entering paste mode (ctrl-D to finish)

object Main extends App {
  for (i <- g) println(i)
}

// Exiting paste mode, now interpreting.

defined object Main

scala> Main main null
43

That's the easy idiom to block for your answer. The main thread won't exit until it has it. Use map to transform a future value.



标签: scala future