如何将任何数字转换为长数

use*_*956 10 scala type-conversion

假设我有:

val number:AnyVal
Run Code Online (Sandbox Code Playgroud)

我知道x可以是任何数字(对于我们的目的,一个Float,Double,Int,Long).

将这样的数字转换为Long的最简单方法是什么:

val l = number.toLong   //fails for AnyVal
Run Code Online (Sandbox Code Playgroud)

and*_*ndy 16

如果你知道它肯定会是Float,Double,Int或Long,你可以将它强制转换为数字.然后你可以调用longValue:

val number:AnyVal = 10
val l:Long = number.asInstanceOf[Number].longValue
Run Code Online (Sandbox Code Playgroud)


Ran*_*ulz 12

怎么样:

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$1$$anonfun$apply$1.apply$mcJ$sp(<console>:14)
    at $anonfun$1$$anonfun$apply$1.apply(<console>:14)
    at $anonfun$1$$anonfun$apply$1.apply(<console>:14)
    at scala.util.Try$.apply(Try.scala:161)
    at $anonfun$1.apply(<console>:14)
    at $anonfun$1.apply(<console>:14)
    at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:244)
    at scala.collection.TraversableLike$$anonfun$map$1.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)
Run Code Online (Sandbox Code Playgroud)