Created
January 18, 2015 04:48
-
-
Save shigemk2/4af5a2a5c9d25ba2c386 to your computer and use it in GitHub Desktop.
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
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