Const function arguments in java?

jdm picture jdm · Dec 28, 2016 · Viewed 7.5k times · Source

Is there a way to achive something similar to C++'s const in Java? Specifically, I have a function like

private static Vector2 sum(Vector2 vec1, Vector2 vec2) {
    return vec1.cpy().add(vec2);
}

and I want to

  1. make clear in the signature that it doesn't modify it's arguments,
    and
  2. enforce that it doesn't modify it's arguments (preferably at compile time, but inserting runtime assertions would also be OK).

Now I know that java is strictly pass-by-reference (I'm just teasing, I know it is pass-by-value or rather pass-by-copying-a-reference of course). What I mean is that in Java, when you call a method, the reference is copied, but that reference points to the same object contents. If a class has public fields or setters, a called method can always modify the contents of a passed object. Is there any e.g. annotation like @NotNull or tool to prevent this? I just found the JetBrains annotations like @Contract(pure = true), but I don't think they provide any checking.

Answer

Orest Savchak picture Orest Savchak · Dec 28, 2016

You can not guarantee that method won't change the parameters. If you want to avoid changing the object, you should make it immutable. You can use some wrapper classes to be passed inside, without provided setters. Or you can make your setters package-local and use some access helper classes in the same package if you need to call some package-local method.