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:

import kotlin.random.Random

// We'll show how references work in contrast to values with
// 2 functions: `zeroval` and `zeroref`.
// `zeroval` has an Int parameter, so arguments will be passed to it by
// value. `zeroval` will get a copy of `ival` distinct
// from the one in the calling function.
fun zeroval(ival: Int) {
    var localIval = ival  // Create a local copy
    localIval = 0  // This only affects the local copy
}

// `zeroref` in contrast has a MutableInt parameter, which is passed by reference.
// Changing the value inside the function will affect the original variable.
class MutableInt(var value: Int)

fun zeroref(iref: MutableInt) {
    iref.value = 0
}

fun main() {
    var i = 1
    println("initial: $i")

    zeroval(i)
    println("zeroval: $i")

    // Create a MutableInt to simulate a reference
    val iref = MutableInt(i)
    zeroref(iref)
    i = iref.value
    println("zeroref: $i")

    // In Kotlin, we don't have direct access to memory addresses,
    // so we'll use a random number to simulate a unique identifier
    println("identifier: ${Random.nextInt()}")
}

In this Kotlin version:

  1. We use a regular Int for zeroval, which is passed by value.
  2. We create a MutableInt class to simulate a reference for zeroref.
  3. Instead of using the & operator to get a memory address, we create a MutableInt object.
  4. We use string interpolation ($variable) for easier string formatting.
  5. 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:

initial: 1
zeroval: 1
zeroref: 0
identifier: 1804289383

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.