Created
July 23, 2012 03:28
-
-
Save gkojax/3161880 to your computer and use it in GitHub Desktop.
case文とtry catchがネストしてるの
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def string2Int(sizeString: Option[String]): Option[Int] = { | |
sizeString match { | |
case Some(a) => | |
try { | |
val size = a.toInt | |
Option(size) | |
} catch { | |
case _ => | |
None | |
} | |
case _ => | |
None | |
} | |
} | |
string2Int(Option("123")) // Some(123) | |
string2Int(Option("rrr")) // None | |
string2Int(None) // None |
import scala.util.control.Exception._
def string2Int(sizeString: Option[String]): Option[Int] = for {
size <- sizeString
sizeInt <- allCatch.opt(size.toInt)
} yield sizeInt
こんな感じですかね?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
こんなのを使えばちょっとシンプルになります
import scala.util.control.Exception._
catching(classOf[NumberFormatException]).opt(Option(a.toInt)).getOrElse(None)