AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |
Back to Blog
Kotlin any type9/5/2023 If this wasn't the case then there would be an exception. This cast is safe but only because M圜lassB is a derived class of M圜lassA. Now myObjectA actually references an object of type M圜lassB, but this doesn't matter as all of the methods that you can use are present in myObjectB. So as long as myObjectB has been created: Kotlin allows you to cast an object to a new type using the as operator. Put another way upcasting is a safe operation. The variable myObjectA can reference an object of type M圜lassB by referencing the instance of M圜lassA within.Ī derived class can always be used in place of a base class. As an object of M圜lassB has all of the methods and properties of M圜lassA objects, we can allow the variable myObjectA to reference an object of M圜lassB. If we keep things very simple it could only reference an object of type M圜lassA but this would be very restrictive. This declares the variable myObjectA to be of type M圜lassA but at the moment it doesn't reference anything. The type of the variable used to reference an object and the type of the object being referenced. There are always two possible types to consider. If you find you are having problems understanding casting then make sure that you keep in mind the following: In fact casting is slightly more subtle than this as it involves an object of a given type and a variable that references the object which can be of a different declared type. Casting is the general practice of treating one object as if it was an object of another type.
0 Comments
Read More
Leave a Reply. |