Scala 学习笔记之集合 Try和Future
Posted AK47Sonic
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Scala 学习笔记之集合 Try和Future相关的知识,希望对你有一定的参考价值。
import util._ import concurrent.ExecutionContext.Implicits.global import concurrent.Future import concurrent.duration._ object CollectionDemo9 { def main(args: Array[String]): Unit = { //Try捕捉异常 println(Try(10 / 0)) println(Try(10).flatMap { x => Try(x + "abc") }) println(Try(10 / 0).flatMap { x => Try(x + "abc") }) //会丢Exception println(Try(10).toOption) println(Try(10).map { x => x + 2 }) println(Try(10 / 0) match { case Success(x) => x case Failure(error) => -1 }) //Future使用, 异步5秒后会打印hi Future { Thread.sleep(3000); println("hi") } println("waiting") Thread.sleep(5000) //异步执行Future, 并用回调函数获得结果 def sayHello(s: String): String = { Thread.sleep(3000) s + " call Future" } val futureCaller = Future sequence Seq(Future(sayHello("sky")), Future(sayHello("bill"))) futureCaller onSuccess { case Seq(x, y) => println(x + "," + y) } println("waiting again") Thread.sleep(5000) //同步调用Future, 如果在指定时间异步调用返回结果,则返回结果。 val maxTime = Duration(10, SECONDS) println(concurrent.Await.result(Future(sayHello("sky")), maxTime)) //同步调用Future, 如果在指定时间异步调用没有返回结果,则抛出异常。 val maxTime1 = Duration(2, SECONDS) println(concurrent.Await.result(Future(sayHello("sky")), maxTime1)) } }
运行结果:
Failure(java.lang.ArithmeticException: / by zero)
Success(10abc)
Failure(java.lang.ArithmeticException: / by zero)
Some(10)
Success(12)
-1
waiting
hi
waiting again
sky call Future,bill call Future
sky call Future
Exception in thread "main" java.util.concurrent.TimeoutException: Futures timed out after [2 seconds]
at scala.concurrent.impl.Promise$DefaultPromise.ready(Promise.scala:219)
at scala.concurrent.impl.Promise$DefaultPromise.result(Promise.scala:223)
at scala.concurrent.Await$$anonfun$result$1.apply(package.scala:107)
at scala.concurrent.BlockContext$DefaultBlockContext$.blockOn(BlockContext.scala:53)
at scala.concurrent.Await$.result(package.scala:107)
at com.citi.scala.CollectionDemo9$.main(CollectionDemo9.scala:43)
at com.citi.scala.CollectionDemo9.main(CollectionDemo9.scala)
以上是关于Scala 学习笔记之集合 Try和Future的主要内容,如果未能解决你的问题,请参考以下文章