简体   繁体   English

输入与Scala Try不匹配的内容

[英]Type mismatches with Scala Try

Below, I am trying to extract a Tweet JSON field retweeted_status . 下面,我试图提取一个Tweet JSON字段retweeted_status I check if the JSON contains the field and then use Try to extract it. 我检查JSON是否包含该字段,然后使用Try提取它。 I would like to assign the extracted value on success to the var retweet_count and on failure, assign retweet_count as 0. But when I try this case Success(result)=> retweet_count = result I get a mismatch error stating that BigInt cannot match with Unit. 我想将提取的成功值分配给var retweet_count并在失败时将retweet_count指定为0.但是当我尝试这种case Success(result)=> retweet_count = result我得到一个不匹配错误,指出BigInt与Unit不匹配。

Printing out the class of retweeted_favorite_count2 I get scala.runtime.BoxedUnit . 打印出retweeted_favorite_count2的类我得到了scala.runtime.BoxedUnit What is the work around this? 围绕这个是什么工作?

var retweet_count: BigInt= 0
if (value.has("retweeted_status")){
  val retweeted_favorite_count0 = value\"retweeted_status"\"favorite_count"
  val retweeted_favorite_count1 = Try(retweet_count=retweeted_favorite_count0.extract[BigInt])
  val retweeted_favorite_count2 = retweeted_favorite_count1 match {
                case Success(result)=> result
                case Failure(exception)=> 0
                case _=> 0
              }
  println(" retweeted_favorite_count2"+ retweeted_favorite_count2.getClass )

The contents of your Try is an assignment: retweet_count=... Assignments have no meaningful return value so the result in Success(result) is not an Int . 你的内容Try是赋值: retweet_count=...分配没有意义的返回值,所以resultSuccess(result)是不是一种Int

You can get around this by making the assignment after assessing the Try . 您可以在评估Try之后进行任务来解决这个问题。

val retweeted_favorite_count2 =
  Try(retweeted_favorite_count0.extract[BigInt]) match {
    case Success(result)=> 
      retweet_count = result
      result
    case Failure(_)=> 0
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM