码迷,mamicode.com
首页 > 其他好文 > 详细

scala try monad

时间:2015-05-01 00:26:05      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:

当输入的数据格式不正确时,ActivityData 中会出现 OutofIndex 错误,但更多的时候我们只关心想要的结果而不想了解出现了怎样的错误,然后会写出这样的代码
 
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
  }
}
 
而 import scala.util.Try 后,我们可以写出这样的代码
 
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)
  }
}
 
就像 Option 一样,Try 有 success 和 fail 两种可能性,而且用法也和 Option 类型
 
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)
}
 
我们能这么做的原因是 Try 是 monad,当一切正常时,它返回 Success(something), 失败时返回 Failure(error)

scala try monad

标签:

原文地址:http://www.cnblogs.com/xinsheng/p/4470103.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!