未来方法参数的默认值

时间:2018-12-16 01:18:46

标签: scala

是否可以为Future类型的方法参数提供默认值?

我们可以做到:

def myMethod(test: String = "") {...}

但是如果我们有未来的话

def myMethod(test: Future[List[Color]]) {...} //How can I set default for this?

1 个答案:

答案 0 :(得分:4)

<?php date_default_timezone_set('Europe/Berlin'); echo "Europe/Berlin:\n"; echo "gmdate: ".gmdate('d.m.y H:i', 0) . "\n"; echo "date: ".date('d.m.y H:i', 0) . "\n"; date_default_timezone_set('America/Los_Angeles'); echo "\nAmerica/Los_Angeles:\n"; echo "gmdate: ".gmdate('d.m.y H:i', 0) . "\n"; echo "date: ".date('d.m.y H:i', 0) . "\n"; /* OUTPUT: Europe/Berlin: gmdate: 01.01.70 00:00 date: 01.01.70 01:00 America/Los_Angeles: gmdate: 01.01.70 00:00 date: 31.12.69 16:00 */ 将包含

  • Future[A]类型的成功结果
  • throwable类型的失败结果

示例:

A

这意味着您可以在示例中将默认值分配为scala> import scala.concurrent.Future import scala.concurrent.Future scala> val success = Future.successful("some data") success: scala.concurrent.Future[String] = Future(Success(some data)) scala> val failed = Future.failed(throw new Exception("failed")) java.lang.Exception: failed ... 30 elided

Future.successful

示例:

def myMethod(test: Future[List[Color]] = Future.successful(List.empty[Color])) {...}

在代码库中,始终将已计算的结果标记为scala> implicit val ec = scala.concurrent.ExecutionContext.global ec: scala.concurrent.ExecutionContextExecutor = scala.concurrent.impl.ExecutionContextImpl$$anon$3@3c8802cf[Running, parallelism = 8, size = 0, active = 0, running = 0, steals = 0, tasks = 0, submissions = 0] scala> def addLoyaltyPoints(previousLoyalty: Future[Int] = Future.successful(0)): Future[Int] = previousLoyalty.map(_ + 2) addLoyaltyPoints: (previousLoyalty: scala.concurrent.Future[Int])scala.concurrent.Future[Int] scala> addLoyaltyPoints() res16: scala.concurrent.Future[Int] = Future(<not completed>) scala> res16 res17: scala.concurrent.Future[Int] = Future(Success(2)) 而不是Future.successful(a)总是一个好习惯,因为Future(a)将在线程上运行。为预先计算的结果分配线程是没有意义的。