Skip to content

Instantly share code, notes, and snippets.

@gkojax
Created July 23, 2012 03:28
Show Gist options
  • Save gkojax/3161880 to your computer and use it in GitHub Desktop.
Save gkojax/3161880 to your computer and use it in GitHub Desktop.
case文とtry catchがネストしてるの
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
@sndyuk
Copy link

sndyuk commented Jul 23, 2012

こんなのを使えばちょっとシンプルになります

import scala.util.control.Exception._

catching(classOf[NumberFormatException]).opt(Option(a.toInt)).getOrElse(None)

@gakuzzzz
Copy link

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