Any differences between asInstanceOf[X] and toX for value types?

后端 未结 2 873
不知归路
不知归路 2021-02-19 11:56

I used IntelliJ\'s ability to convert Java code to Scala code which generally works quite well.

It seems that IntelliJ replaced all casts with calls to asInstanceO

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-19 12:41

    Well, toInt and toLong are not casts. The correct conversion of type casting is asInstanceOf indeed. For example:

    scala> val x: Any = 5
    x: Any = 5
    
    scala> if (x.isInstanceOf[Int]) x.asInstanceOf[Int] + 1
    res6: AnyVal = 6
    
    scala> if (x.isInstanceOf[Int]) x.toInt + 1
    :8: error: value toInt is not a member of Any
           if (x.isInstanceOf[Int]) x.toInt + 1
                                      ^
    

提交回复
热议问题