gpt4 book ai didi

scala - 如何将任何数字转换为长整数

转载 作者:行者123 更新时间:2023-12-04 02:37:56 26 4
gpt4 key购买 nike

假设我有:

val number:AnyVal

我知道 x 可以是任何数字(就我们而言,浮点数、 double 、整数、长整数)。

将此类数字转换为 Long 的最简单方法是什么:
val l = number.toLong   //fails for AnyVal

最佳答案

怎么样:

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)

关于scala - 如何将任何数字转换为长整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19647525/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com