Whenever we perform type-casting, we should keep in mind that it is a potential source of exceptions. That's the reason why we should always perform type-checking using the is modifier or do the casting inside the try…catch block. However, in Kotlin, we have also a safe casting option that will not throw ClassCastException but will return null instead. In this recipe, we are going to test the safe casting in action.
Safe type-casting
How to do it...
- Let's start by defining a function that returns a Number type of a random Double value:
fun getRandomNumber(): Number = Random().nextDouble() * 10
- Try to cast the results of the function to different types using the safe-cast operator and print the casted...