![]() ![]() ![]() Long – doubling the value, returning obj * 2.String – duplicating the string and returning obj + obj.Depending on obj‘s concrete type, we’d like to apply different operations: Let’s say we receive an object ( obj) in the type Any. So, again, let’s understand the usage of as? with a function and a test: fun safeCastToString(obj: Any): String? = obj as? StringĪssertThat(unsafeCastToString(aLong)).isNull()Īs we can see in the test above, this time, when we attempt to cast a Long object to String, we’ve got a null value. However, in Kotlin, we can use the safe cast operator as? to achieve it. In Java, we can do that by catching the ClassCastException and returning null. Instead, we would like to have a null value. ![]() Sometimes, if the type casting fails, we don’t want the function to throw an exception. Also, we use Kotlin’s assertFailsWith function to verify if the ClassCastException is thrown. Next, let’s test it: val aString: Any = "I am a String"ĪssertThat(unsafeCastToString(aString)).isEqualTo(aString)Īs the test above shows, we pass a String and then a Long to the function. Fun unsafeCastToString(obj: Any): String = obj as String ![]()
0 Comments
Leave a Reply. |