Return Scala 中 JSON 的值(akka 和 spray)
Return value from JSON in Scala (akka and spray)
我不知道该说什么。连续第二天,我尝试从 JSON 对象中获取值,同时处理许多 Scala 库。这是 Akka
和 spray
。我尝试将 where on earth id 保存到变量中,并从 function/method 中保存 return。是否 Future
对我来说并不重要,但我坚持这个说法 int = for {lel <- ss} yield lel
。无论我尝试什么,我总是得到 int
的初始值,无论它是 class、case class、Future[Int] 还是 Int。请指教
scala> def queryLocation(location: String): Future[Int] = {
| var int: Any = Future{0} ; val locUri = Uri("https://www.metaweather.com/api/location/search/").withQuery(Uri.Query("query" -> location))
|
| val req = HttpRequest(uri = locUri, method = HttpMethods.GET);val respFuture = Http().singleRequest(req);
| respFuture.onComplete{
| case Success(value) => {
| val r = Unmarshal(value).to[Seq[Search]]
| val ss = for { reich <- r } yield reich(0).woeid
| int = for {lel <- ss} yield lel
| }
| }
| int.asInstanceOf[Future[Int]] }
respFuture.onComplete{
^
On line 5: warning: match may not be exhaustive.
It would fail on the following input: Failure(_)
def queryLocation(location: String): scala.concurrent.Future[Int]
scala> Await.result(queryLocation("Warsaw"), 1.second)
val res221: Int = 0
问题是您创建了一个急切执行的 Future:
var int: Any = Future{0}
我在这里看到不同的问题:
- 不要使用变量。 Future 是一种异步计算,改变其中的任何内容是没有意义的。
- 为什么要将变量声明为 Any?。这是一个未来。
而这个为了理解:
int = for {lel <- ss} yield lel
看起来很糟糕。也许是因为 Scala 的未来不是引用透明的。所以要避免这种情况。如果你想反序列化响应的内容,只需使用 map:
val future = HttpRequest(uri = locUri, method = HttpMethods.GET).map(content => Unmarshal(value))
Await.result(future, 1.second)
我不知道该说什么。连续第二天,我尝试从 JSON 对象中获取值,同时处理许多 Scala 库。这是 Akka
和 spray
。我尝试将 where on earth id 保存到变量中,并从 function/method 中保存 return。是否 Future
对我来说并不重要,但我坚持这个说法 int = for {lel <- ss} yield lel
。无论我尝试什么,我总是得到 int
的初始值,无论它是 class、case class、Future[Int] 还是 Int。请指教
scala> def queryLocation(location: String): Future[Int] = {
| var int: Any = Future{0} ; val locUri = Uri("https://www.metaweather.com/api/location/search/").withQuery(Uri.Query("query" -> location))
|
| val req = HttpRequest(uri = locUri, method = HttpMethods.GET);val respFuture = Http().singleRequest(req);
| respFuture.onComplete{
| case Success(value) => {
| val r = Unmarshal(value).to[Seq[Search]]
| val ss = for { reich <- r } yield reich(0).woeid
| int = for {lel <- ss} yield lel
| }
| }
| int.asInstanceOf[Future[Int]] }
respFuture.onComplete{
^
On line 5: warning: match may not be exhaustive.
It would fail on the following input: Failure(_)
def queryLocation(location: String): scala.concurrent.Future[Int]
scala> Await.result(queryLocation("Warsaw"), 1.second)
val res221: Int = 0
问题是您创建了一个急切执行的 Future:
var int: Any = Future{0}
我在这里看到不同的问题:
- 不要使用变量。 Future 是一种异步计算,改变其中的任何内容是没有意义的。
- 为什么要将变量声明为 Any?。这是一个未来。
而这个为了理解:
int = for {lel <- ss} yield lel
看起来很糟糕。也许是因为 Scala 的未来不是引用透明的。所以要避免这种情况。如果你想反序列化响应的内容,只需使用 map:
val future = HttpRequest(uri = locUri, method = HttpMethods.GET).map(content => Unmarshal(value))
Await.result(future, 1.second)