Introduction to references
There might be a nagging thought in your mind at this point. Look at the two functions from the Shipyard
class again:
fun serviceDestroyer(destroyer: Destroyer){ destroyer.serviceShip() } fun serviceCarrier(carrier: Carrier){ carrier.serviceShip() }
When we called those functions and passed the friendlyDestroyer
and friendlyCarrier
to their appropriate service…
function, we saw, from the before and after output, that the values inside the instances were changed. Usually, if we want to keep the result from a function, we need to use the return value. What is happening is that, unlike a function that has regular types as parameters, when we pass an instance of a class, we are really passing a reference to the instance itself – not just copies of the values within it, but the actual instance.
Furthermore, all the different ship-related instances were declared with val
, so how did we change any of the properties at all? The short answer to this conundrum...