Constant function arguments in java?

Is there a way to achieve something like C ++ const in Java? In particular, I have a function like

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

I want too

  • specify in the signature that he does not change her arguments,
    and
  • make sure it does not change its arguments (preferably at compile time, but inserting runtime statements will also be ok).

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

+5
source share
3 answers

You cannot guarantee that this method will not change the parameters. If you want to avoid changing the object, you must make it immutable. You can use some wrapper classes that need to be passed internally without providing setters. Or you can make your setters local packages and use some helper access classes in a single package if you need to call some package-local method.

+3
source

You can add final to the parameter, but this will only prevent their initialization, you can still call the method and setter, changing the contents of your Vector .

If you need to restrict access to them, you may need to create an immutable class that hides the Vector wrapper . Basically, it redirects only those methods that prevent any update, hiding the installer and restricting getter to primitive values, returning an instance, makes it possible to change the value in it.

Of course, there is some decisive solution, you can clone a vector and its content. Saving instances is safe, even if someone is trying to update some values. This will only be a problem during this call, using the wrong values, but will keep the original instances intact.

Or you could use both solutions by creating a wrapper that returns the cloned instance (you just need to provide get (int index), which returns the clone). This solution is a compromise between memory consumption (cloning only the required instance) and restrictive getter.

+2
source

In Java, the only way to do this is to have a read-only interface as well as a mutable one. This is not easy to maintain, and const will be much nicer, but it is not available. You can write

 interface ReadOnlyVector<T> { int size(); // getter methods T get(int n); default ReadOnlyVector<T> add(ReadOnlyVector<T> v) { // add two vectors are create a new one. } } interface Vector<T> extends ReadOnlyVector<T> { // mutating methods. void add(T t); } 
0
source

Source: https://habr.com/ru/post/1261983/


All Articles