concept reference in category kotlin

This is an excerpt from Manning's book The Joy of Kotlin.
I said at the start of section 2.1 that
valmeans that the reference is immutable. Does this mean that all references are always immutable? No, but you should usevalas much as possible. The reason is that if a reference can’t change, there’s no way to mess with it once it’s been initialized. For the same reason, you should initialize references as soon as possible. (Although, as you’ll see, Kotlin generally prevents using uninitialized references. This differs from Java, which automatically sets uninitialized references tonulland lets you use them.)
Most data is represented by a reference pointing to it, so the most obvious way to represent the absence of data is to use a pointer to nothing. That’s what we call a null pointer. In Kotlin, a reference is a pointer to a value.
In most programming languages, references can be changed to point to a new value. For this reason, the term variable is often used as a replacement for reference. The word variable is not much of a problem when all references can be later reassigned to a new value. In such cases, it’s normal to use the term variable as a replacement for reference. But that can be different when you use references that can’t be reassigned. In such a case, you end up with two types of variables: those that can vary and those that cannot. It’s then safer to use the term reference.
Listing 13.5 The
Playerclassprivate class Player(id: String, #1 private val sound: String, #2 private val referee: Actor<Int>): AbstractActor<Int>(id) { #3 override fun onReceive(message: Int, sender: Result<Actor<Int>>) { println("$sound - $message") #4 if (message >= 10) { referee.tell(message, sender) #5 } else { sender.forEach( { actor: Actor<Int> -> #6 actor.tell(message + 1, self()) }, { referee.tell(message, sender) } #7 ) } } } #1 The class is private because it’s defined at package level. You could also define it as a local class, inside the main function of the program. #2 The Sound string is a message that’s displayed by the players when they receive the ball (either Ping or Pong). #3 Each player is created with a reference to the referee so that a player can give the ball back to the referee when the game is over. This wouldn’t be necessary if the Player class was defined locally in the same function as the referee (for example, in the main function). #4 This is the business part of the actor, meaning the part that does what the user expects to see. #5 If the game is over, gives the ball back to the referee. #6 Otherwise, sends it back to the other player if present. #7 If the other player isn’t present, registers an issue with the referee.