12/30/2023 0 Comments Kotlin any typeIf the attempt fails, a ClassCastException will be thrown. Unsafe Cast is the attempt to convert the type of a variable to another using the as keyword. Smart Cast is the automatic deduction of the type by the Kotlin compiler after a check with is. ![]() In Kotlin, the instanceof keyword no longer exists and is replaced by is. □ Already finished? The corrected version is right here. □ How about a little exercise? This is where you can find it. Theory is good, but practice is even better! We’ve prepared a small interactive exercise at the end of the chapter so that you can apply all this new knowledge. Rather efficient, if I do say so myself! Practice Makes Perfect! Print(message) Result of the second approach: the Kotlin compiler assigns a null value to the variable val anyObject: Any = "Hello, Kotlin students!" It will allow us to perform a safe cast thanks to the keyword as followed by a question mark ? in order to explicitly tell the Kotlin compiler that, if the conversion fails, it will have to assign a null value to our variable. The second approach is more Kotlin-friendly. A Smart Conversion? private fun getDefaultSize(anyObject: Any): Int Result of the first approach: an error message is triggered I’m getting there! Let’s write the same method right away, but in Kotlin. OK, I had figured that out all by myself! But what does this have to do with Kotlin and this chapter?
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |