简体   繁体   中英

Try to understand scala syntax with blocks

I'm a beginner in scala and I'm trying to understand this syntax :

val f = Future {
  Thread.sleep(Random.nextInt(500))
  42
}

println("2- before onComplete")
f.onComplete {
  case Success(value) => println(s"Got the callback, meaning = $value")
  case Failure(e) => e.printStackTrace
}

Please explain these 2 blocks inside Future{...} and onComplete{...}

Thanks a lot

In scala every statement is expression. Blocks are expressions also. Every expression has return value. These blocks will do something in blocks and return some values. In Future block, it creates Future object witch contains 2 operations: sleep for random milliseconds and returns 42. In onComplete method block means handling two cases of Future evaluation, on success and on failure statements. If future will throw an error or evaluation will interrupted, Failure case will evaluate. If future evaluated successfully Success case will evaluate. Return value in both cases is Unit it's analogue of void .

The first block is equal to something like that:

def code(): Int = {
  Thread.sleep(Random.nextInt(500))
  42
}
val f = Future(code)

Block acts like an anonymous function but it not reuqires to declare a function, it is just a syntax sugar. So future f eagerly evaluates contents of a block asynchronously starting at the point of declaration. Ie if random will yield a number n which is 0 < n < 500 , future execution will be suspended for n milliseconds and then resumed and number 42 will be returned and set as a result of a Future.

As futures are non-blocking, while execution context of your future working on your future f , the main thread will run line

println("2- before onComplete") 

and you will see this line in the console. Then, the second block uses pattern matching to create a function that acts from Try[Int] to Unit, as it defined on both Success and Failure constructors of Try , it is an equivalent to:

f.onComplete { ttry => 
  ttry match {
    case Success(value) => println(s"Got the callback, meaning = $value")
    case Failure(e) => e.printStackTrace
  }
}

Note that you must await your future till application termination to ensure onComplete block execution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM