Pass by value — explained

A simple example to show how Kotlin and Java pass arguments by value to functions and not by reference.

Photo by Lalaine Macababbad on Unsplash

In a discussion about a shared mutable state, I recently got asked about pass-by-value and that objects are essentially passed by reference and how come that is and how it works on the JVM in Kotlin.

I can understand that one might think that an object is passed by reference since both the caller and callee share the same underlying object, and altering that object is one of the problems with shared mutable state.

To explain how Kotlin passes objects by value, I came up with a trivial yet smart example to show how it works.

TLDR; It is a copy of the pointer that is passed to the function and not a copy of the actual object. (Therefore the underlying object is shared and dangerous in a threaded environment).

The example is a “nulling” function. A function that takes an object and nulls it. Like cleaning up by releasing references to an object. The biggest problem whit this example is that it can’t be written easily in Kotlin, but the concept is the same in Java.

Temp ref = new Temp();
System.out.println(ref); // Is not null
void nuller(Temp value) {
value = null;

It means that it’s not the reference that is sent to the function named “nuller” it’s a copy of the pointer. And nulling the pointer won’t null the original pointer (reference). I.e., the arguments to the function are passed by value and not by reference.

Trying this in Kotlin, the compiler will help you out by saying that you can’t reassign a val. So Kotlin declares the arguments to functions as values, equivalent to java finals.

We can go around it in some sense by nesting or proxying, but the top-most object reference we can never delegate to some other function for nulling. We will get a copy of the pointer.

For clarity, let us also look at an example of pass by reference. There aren’t a lot of languages that allow passing by reference, but c++ does.

void swap(int& x, int& y) 
int x1 = x;
x = y;
y = x1;

int main()
int a = 9, b = 1;
cout << "a is " << a; // outputs: a is 9
swap(a, b);
cout << "a is " << a; // outputs: a is 1

I’ll challenge you to do that in Kotlin or Java. The biggest problem in this discussion is what wording to use. As a pointer in Kotlin or Java often is referred to as a reference, it clashes with “pass by reference.”

Thank you for your time!
→ Bob

Lead Developer at Qvik, Coach, Agile Thinker, GDG Lead.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store