scala 如何将任何数字转换为长整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19647525/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert any a number to a long
提问by user48956
Suppose I have:
假设我有:
val number:AnyVal
and I know x may be any number (for our purposes, a Float, Double, Int, Long).
而且我知道 x 可以是任何数字(就我们而言,Float、Double、Int、Long)。
What's the easiest way to convert such a number to a Long:
将此类数字转换为 Long 的最简单方法是什么:
val l = number.toLong //fails for AnyVal
回答by andy
You can cast it to a Number if you know it's definitely going to be a Float, Double, Int, or Long. Then you can call longValue:
如果您知道它肯定是 Float、Double、Int 或 Long,则可以将其转换为 Number。然后你可以调用longValue:
val number:AnyVal = 10
val l:Long = number.asInstanceOf[Number].longValue
回答by Randall Schulz
How about:
怎么样:
scala> import scala.util.Try
import scala.util.Try
scala> val i1: Int = 23
i1: Int = 23
scala> val l1: Long = 42
l1: Long = 42
scala> val f1: Float = 14.9f
f1: Float = 14.9
scala> val d1: Double = 14.96
d1: Double = 14.96
scala> val b1: Boolean = true
b1: Boolean = true
scala> List(i1, l1, f1, d1, b1) map (x => Try(x.asInstanceOf[Number].longValue)) foreach (println(_))
Success(23)
Success(42)
Success(14)
Success(14)
Failure(java.lang.ClassCastException: java.lang.Boolean cannot be cast to java.lang.Number)
scala> List(i1, l1, f1, d1, b1) map (x => Try(x.asInstanceOf[Number].longValue)) foreach (n => println(n.get))
23
42
14
14
java.lang.ClassCastException: java.lang.Boolean cannot be cast to java.lang.Number
at $anonfun$$anonfun$apply.apply$mcJ$sp(<console>:14)
at $anonfun$$anonfun$apply.apply(<console>:14)
at $anonfun$$anonfun$apply.apply(<console>:14)
at scala.util.Try$.apply(Try.scala:161)
at $anonfun.apply(<console>:14)
at $anonfun.apply(<console>:14)
at scala.collection.TraversableLike$$anonfun$map.apply(TraversableLike.scala:244)
at scala.collection.TraversableLike$$anonfun$map.apply(TraversableLike.scala:244)
at scala.collection.immutable.List.foreach(List.scala:318)
at scala.collection.TraversableLike$class.map(TraversableLike.scala:244)
at scala.collection.AbstractTraversable.map(Traversable.scala:105)
at .<init>(<console>:14)
回答by richj
Updated answer for Scala 2.11
Scala 2.11 的更新答案
My original answer does not work in newer versions of Scala because the implicit conversion to RichLong is no longer available.
我原来的答案在较新版本的 Scala 中不起作用,因为到 RichLong 的隐式转换不再可用。
This updated version works for numbers via type matching for Number sub-types and also for Strings via an implicit conversion in Scala 2.11:
此更新版本通过数字子类型的类型匹配适用于数字,也适用于通过 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.")
}
// Test cases
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")
}
}
The matching technique is a minor variation on the casting technique used in other answers.
匹配技术是其他答案中使用的铸造技术的微小变化。
Original answer for older versions of Scala
旧版本 Scala 的原始答案
Attempting implicit conversion to RichLong in a match block seems to work quite nicely:
尝试在匹配块中隐式转换为 RichLong 似乎工作得很好:
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 might also be possible to add a case for matching a String in numeric format if you wanted to cater for that possibility.
如果您想满足这种可能性,也可以添加一个案例来匹配数字格式的字符串。
回答by Daniel C. Sobral
If you don't have any information about the more specific type, then you'll have to pattern match against each option.
如果您没有关于更具体类型的任何信息,那么您必须对每个选项进行模式匹配。

