Skip to content

Instantly share code, notes, and snippets.

@shigemk2
Created January 18, 2015 04:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shigemk2/4af5a2a5c9d25ba2c386 to your computer and use it in GitHub Desktop.
Save shigemk2/4af5a2a5c9d25ba2c386 to your computer and use it in GitHub Desktop.
val hundred = "100"
println(hundred, hundred.getClass)
println(hundred.toInt, hundred.toInt.getClass)
println(hundred.toDouble, hundred.toDouble.getClass)
println(hundred.toFloat, hundred.toFloat.getClass)
val one = "1"
println(one, one.getClass)
println(one.toInt, one.toLong.getClass)
println(one.toShort, one.toShort.getClass)
println(one.toByte, one.toByte.getClass)
val aString = "hoge"
// not required to declare "throws NumberFormatException"
def toInt(s: String):Option[Int] = {
try {
Some(s.toInt)
} catch {
case e: NumberFormatException => None
}
}
toInt(aString) match {
case Some(n) => println(n)
case None => println("Boom! That wasn't a number.")
}
// assign the result to x
val x = toInt(aString)
println(toInt("1").getOrElse(0)) // 1
println(toInt("a").getOrElse(0)) // 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment