将回调传递给函数以在Scala将来的onComplete方法中注册 [英] Pass callback into function to register on scala future onComplete method

查看:163
本文介绍了将回调传递给函数以在Scala将来的onComplete方法中注册的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要在scala未来上使用 onComplete 方法,如此处

I was to use the onComplete method on a scala future, as described here.

基本概念如下:

def getPosts(url: String, callback: Try[HttpResponse[String]] => Unit) {
  val f: Future[[HttpResponse[String]]] = Future {
    val response: HttpResponse[String] = Http(url).get()
    if (response.code > 399) {
      throw new Exception(s"Error sending to ${url}")
    }

    response
  }

  f onComplete callback
}

val cb= {
  case Success(response : HttpResponse[String]) => succesfulWrites += 1
  case Failure(err) => totalFailedWrites += 1
}

getPosts("localhost:8000/widgets", cb)

但是,我不断遇到错误,例如缺少扩展功能的参数类型。匿名函数的参数类型必须是完全已知的。(关于我在其中定义 val onComplete 的行),或其他类似的错误提示我我做错了。

However, I keep getting errors such as missing parameter type for expanded function. The argument types of an anonymous function must be fully known. (regarding the line where I define val onComplete), or other similar errors saying I'm doing it wrong.

当我刚接触Scala时,我意识到我可能会误解执行此操作的最佳方法。虽然很难找到示例,但似乎很难用。我是否在错误地考虑Scala中的期货/回调?如果不是,是否有一个简单的端到端示例(将回调作为arg传递给使用Future的函数)?

As I am new to Scala, I recognize I could just be misunderstanding the best way to do this. I'm having a hard time finding examples though for what seems to be a fairly common use case. Am I thinking about futures/callbacks in scala incorrectly? If not, is there a simple end-to-end example for this scenario (passing callbacks as an arg into a function that uses futures)?

推荐答案

模式匹配匿名函数

{
  case Success(response: HttpResponse[String]) => successfulWrites += 1
  case Failure(err)                            => totalFailedWrites += 1
}

必须显式指定,因此代替

must be explicitly specified, so instead of

val cb = {
  case Success(response: HttpResponse[String]) => successfulWrites += 1
  case Failure(err)                            => totalFailedWrites += 1
}

我们必须写类似

val cb: Try[HttpResponse[String]] => Unit = {
  case Success(response: HttpResponse[String]) => successfulWrites += 1
  case Failure(err)                            => totalFailedWrites += 1
}

这里我假设 getPosts的签名

def getPosts(url: String, callback: Try[HttpResponse[String]] => Unit)

更准确地说,仅 parameter 类型(而不是整个函数类型的返回类型)需要明确提供,这意味着以下内容也可以使用

More precisely only the parameter type (as opposed to also return type of the whole function type) needs to be explicitly provided, meaning the following would also work

val cb = (x: Try[HttpResponse[String]]) => x match {
  case Success(response: HttpResponse[String]) => successfulWrites += 1
  case Failure(err)                            => totalFailedWrites += 1
}

这篇关于将回调传递给函数以在Scala将来的onComplete方法中注册的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆