Scala 2.11
Scala, RichLong .
Number, Scala 2.11:
object LongNumber {
def cast(number: Any): Long = number match {
case n: Number => n.longValue()
case x => throw new IllegalArgumentException(s"$x is not a number.")
}
def main(args: Array[String]): Unit = {
val twelveByte: Byte = 0x0c
val twelveString: String = "12"
println(s"Converting a long: ${cast(12L)}")
println(s"Converting an int: ${cast(12)}")
println(s"Converting a double: ${cast(12.0)}")
println(s"Converting a byte: ${cast(twelveByte)}")
println(s"Converting a string: $twelveString")
}
}
- , .
Original answer for older versions of Scala
Trying to implicitly convert to RichLong in a block of matches seems very nice:
import scala.runtime.RichLong
...
def cast(number: Any): Long = number match {
case n: RichLong => n.toLong
case x => throw new IllegalArgumentException(s"$x is not a number.")
}
It is also possible to add a case for matching strings in numerical format if you want to satisfy this possibility.
richj source
share