Pointers in Kotlin
In Kotlin, we don’t have direct pointers as in some other languages, but we can achieve similar functionality using references and mutable variables. Let’s explore this concept:
In this Kotlin version:
- We use a regular
Int
forzeroval
, which is passed by value. - We create a
MutableInt
class to simulate a reference forzeroref
. - Instead of using the
&
operator to get a memory address, we create aMutableInt
object. - We use string interpolation (
$variable
) for easier string formatting. - Since Kotlin doesn’t provide direct access to memory addresses, we use a random number to simulate a unique identifier.
When you run this program, you’ll see output similar to this:
Note that zeroval
doesn’t change the i
in main
, but zeroref
does because it has a reference to the mutable object. The identifier will be different each time you run the program, simulating a unique memory address.
In Kotlin, most variables are references by default, but for primitive types like Int
, they behave as values. To get reference-like behavior for primitives, we need to wrap them in objects, as demonstrated with MutableInt
.