简体   繁体   中英

Type mismatches with Scala Try

Below, I am trying to extract a Tweet JSON field retweeted_status . I check if the JSON contains the field and then use Try to extract it. 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.

Printing out the class of retweeted_favorite_count2 I get 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 .

You can get around this by making the assignment after assessing the Try .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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