In Scala converting Int to Double using asInstanceOf. Yet the variable cannot be casted

时间:2018-02-03 08:34:11

标签: scala

I am using this function in Scala to multiply each element of list with 100. But when trying to type cast percent val it is giving me error.

  def func[T](listOne: List[T])(implicit numeric: Numeric[T]): List[T] = {
    import numeric._
    val percent = 100.asInstanceOf[T]
    listOne.map { e => e * percent }
  }

This is the ScalaTest written using FlatSpec and Matchers. The first test runs successfully but the second test fails due to Double data type of List but the percent data type still being Int .

  "func" should "return Int list multiplied by 100" in {
    func(list1) should be (List(100, 200))
  }
  it should "return Double list multiplied by 100" in {
    func(list2) should be (List(150, 210))
  }

The Exception given is

java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Double

2 个答案:

答案 0 :(得分:2)

It's working fine for me in the REPL

enter image description here

And the getClass method of x returns Double

enter image description here

Anyway, the proper and easiest way to convert and Int to a Double is .toDouble

enter image description here

答案 1 :(得分:0)

I believe the preferred way to convert Ints to Doubles is to use the Int.toDouble method. The asInstanceOf[] method is intended for up-casting between generations in a class hierarchy. Int and Double to not have such a parent-child relationship (although will have a common parent in AnyVal).