加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – Future.onComplete:无法理解方法签名

发布时间:2020-12-16 18:31:00 所属栏目:安全 来源:网络整理
导读:/** When this future is completed,either through an exception,or a value,* apply the provided function. * * If the future has already been completed,* this will either be applied immediately or be scheduled asynchronously. * * $multipleCal
/** When this future is completed,either through an exception,or a value,*  apply the provided function.
   *
   *  If the future has already been completed,*  this will either be applied immediately or be scheduled asynchronously.
   *
   *  $multipleCallbacks
   *  $callbackInContext
   */
  def onComplete[U](func: Try[T] => U)(implicit executor: ExecutionContext): Unit

基本用法似乎是:

result.onComplete({
    case Success(listInt) => {
      //Do something with my list
    }
    case Failure(exception) => {
      //Do something with my error
    }
  })

此函数似乎对产生副作用很有用,因为它返回Unit(如记录完成)
我不明白的是函数返回的这个类型U是什么.我们提供的函数的返回类型是否真的有用?它是如何被Scala使用的?

同样的问题可能适用于onSuccess和onFailure

编辑:为了更清楚,def onComplete [U](func:Try [T] => U)优于def onComplete(func:Try [T] => Unit)有什么好处?

编辑:

Chirlo是对的,U型的功能更灵活,我们可以更容易地传递不返回Unit的现有功能.

type T = String

def onComplete[U](func: Try[T] => U): Unit = { }
def onComplete2(func: Try[T] => Unit): Unit = { }

// Existing function that does not return Unit
def log[T]( t : Try[T]): Int = 0

onComplete(log) // This compiles fine
onComplete2(log) // This does not compile

解决方法

它使功能更灵活.如果它会返回Unit,你可以传递它的函数Try [T] =>单位,但是通过返回U,你可以传递任何以Try [T]作为参数的函数,你可能已经躺在那里.例如:

def log[T]( t : Try[T]): Int =  //write to file and return 0  if Ok,else 128

此功能有副作用,但也返回一个值.您现在可以将此函数传递给Future,虽然它不返回Unit,但结果会被丢弃但您可以重用已有的函数.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读