Scala try Monad

Source: Internet
Author: User

When the input data format is not correct, there will be a outofindex error in Activitydata, but more often we only care about the desired results and do not want to know what the error, and then write such a code def parseCSV(csv : String) = {    try {      Some {        csv.split( "\n" ).map { line = >          val tokens = line.split( ";" )          ActivityData(tokens( 0 ).toLong, tokens( 1 ).toInt, tokens( 2 ).toInt, tokens( 3 ).toLong)        }      }    } catch {      case _ : Throwable = > None    } }And after import Scala.util.Try, we can write this code. def parseCSV(csv : String) = Try {    csv.split( "\n" ).map { line = >      val tokens = line.split( ";" )      ActivityData(tokens( 0 ).toLong, tokens( 1 ).toInt, tokens( 2 ).toInt, tokens( 3 ).toLong)    } }Like option, Try has two possibilities of success and fail, and the usage and option type parseCSV(csvdata).map { entries = >    //do something with the data }.getOrElse {    BadRequest( "Invalid CSV Data" //this is Play Framework specific (returns a 400 HTTP response with a message) }The reason we can do this is that Try is monad, and when everything is normal, it returns Success (something) and returns Failure (error) when it fails

Scala try Monad

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.