Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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