我有一个接受可变数量参数的函数。第一个是字符串,其余的是数字(Int 或 Double),所以我使用 Any* 来获取参数。我想将数字统一视为 double 数,但我不能只对数字参数使用 asInstanceOf[Double]。例如:
val arr = Array("varargs list of numbers", 3, 4.2, 5)
val d = arr(1).asInstanceOf[Double]
给出:
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Double
有没有办法做到这一点? (该函数需要将所有数字相加)。
最佳答案
斯卡拉的 asInstanceOf
是它的类型转换名称。类型转换不是转换。
你想要的可以这样完成:
val mongrel = List("comment", 1, 4.0f, 9.00d)
val nums = mongrel collect { case i: Int => i case f: Float => f case d: Double => d }
val sumOfNums = nums.foldLeft(0.0) ((sum, num) => sum + num)
关于scala - 使用 asInstanceOf 将 Any 转换为 Double,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20691388/