# Pass a non-final like a final arg?

**URL:** <https://discourse.processing.org/t/pass-a-non-final-like-a-final-arg/10029>\
**Category:** Coding Questions\
**Created:** [April 6, 2019, 11:28am UTC](https://discourse.processing.org/t/pass-a-non-final-like-a-final-arg/10029 "2019-04-06T11:28:18Z")\
**Posts on this page:** 7\
**Page:** 1

<div class="post-metadata">

**Author:** ![Stanlepunk](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/stanlepunk/32/11509_2.png) [@Stanlepunk](https://discourse.processing.org/u/Stanlepunk)\
**Post date:** [April 6, 2019, 11:28am UTC](https://discourse.processing.org/t/pass-a-non-final-like-a-final-arg/10029/1 "2019-04-06T11:28:18Z")

</div>

I try to build a menu where some item can be change during the session or with data from outside unknow before the coding session. So I try to pass a non-final data but that’s don’t work obviously.  
I try to find a way to pass out…but failled.  
Below my problem, the first work but not the second when I try with array String:

```auto
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

JMenuBar menu_bar;
JFrame frame;
String info;
void setup() {
  size(300,300);
  System.setProperty("apple.laf.useScreenMenuBar","true");
  frame = (JFrame) ((processing.awt.PSurfaceAWT.SmoothCanvas)this.getSurface().getNative()).getFrame();
  menu_bar = new JMenuBar();
  frame.setJMenuBar(menu_bar);
  JMenu menu = new JMenu("Menu");
  menu_bar.add(menu);
  JMenuItem menu_item = new JMenuItem("test"); 
  menu.add(menu_item);
  frame.setVisible(true);
  
  info = "stuf can change";
  menu_item.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent ae) {
      println("action event:",info); 
    }
  });
}

```

dont work

```auto
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

JMenuBar menu_bar;
JFrame frame;
String [] info = new String[2];
void setup() {
  size(300,300);
  System.setProperty("apple.laf.useScreenMenuBar","true");
  frame = (JFrame) ((processing.awt.PSurfaceAWT.SmoothCanvas)this.getSurface().getNative()).getFrame();
  menu_bar = new JMenuBar();
  frame.setJMenuBar(menu_bar);
  JMenu menu = new JMenu("Menu");
  menu_bar.add(menu);
  JMenuItem [] menu_item = new JMenuItem[2]; 
  menu_item[0] = new JMenuItem("ABC"); 
  menu_item[1] = new JMenuItem("XYZ");
  for(int i = 0 ; i < menu_item.length ; i++) {
     menu.add(menu_item[i]);
  }
 
  frame.setVisible(true);
  
  info[0] = "go to abc";
  info[1] = "go to xyz";
  for(int i = 0 ; i < menu_item.length ; i++) {
    menu_item[i].addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent ae) {
        println("action event:",info[i]); // Cannot refer to the non-final local variable info defined in an enclosing scope
      }
    });
  }
}

```

---

<div class="post-metadata">

**Author:** ![Stanlepunk](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/stanlepunk/32/11509_2.png) [@Stanlepunk](https://discourse.processing.org/u/Stanlepunk)\
**Post date:** [April 6, 2019, 11:55am UTC](https://discourse.processing.org/t/pass-a-non-final-like-a-final-arg/10029/2 "2019-04-06T11:55:46Z")

</div>

Plus when I try to use a temp String like thats, it’s alway the last String is used.

```auto
info[0] = "go to abc";
  info[1] = "go to xyz";
  for(int i = 0 ; i < menu_item.length ; i++) {
    parser = info[i];
    menu_item[i].addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent ae) {
        
        println("action event:",parser); // return "go to xyz" for all situation
      }
    });
  }

```

---

<div class="post-metadata">

**Author:** ![GoToLoop](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/gotoloop/32/86_2.png) [@GoToLoop](https://discourse.processing.org/u/GoToLoop)\
**Post date:** [April 6, 2019, 4:34pm UTC](https://discourse.processing.org/t/pass-a-non-final-like-a-final-arg/10029/3 "2019-04-06T16:34:33Z")

</div>

Let’s start out w/ the basics, shall we? 👨‍🏫

- When we instantiate a class or an interface at the same time we make modifications to them, that’s called anonymous instantiation.
- Those are local synthetic class instances that, if we dare, can even attempt to access local variables & parameters as well inside their own body.
- Normally, all local variables & parameters cease to exist when their function returns.
- However, if any of them happens to be accessed inside a locally-created class’ body, its lifespan then becomes the same as the instances of that synthetic class.
- Other languages, like JavaScript, call those types of local variables & parameters closures:

> **[Closures](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures)**
>
> A closure is the combination of a function and the lexical environment within which that function was declared.

- However, unlike JS closures, Java only allows `final` 1s to be used as such: [Processing.org/reference/final.html](http://Processing.org/reference/final.html)

---

<div class="post-metadata">

**Author:** ![Stanlepunk](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/stanlepunk/32/11509_2.png) [@Stanlepunk](https://discourse.processing.org/u/Stanlepunk)\
**Post date:** [April 6, 2019, 4:58pm UTC](https://discourse.processing.org/t/pass-a-non-final-like-a-final-arg/10029/4 "2019-04-06T16:58:21Z")

</div>

Thanks teacher !!! That’s mean i’m lock on this way to code a dynamic menu, or I must find an other way to create an `ActionListener()`. But the problem if it is, that’s `ActionListener()`is an `interface` [https://docs.oracle.com/javase/7/docs/api/java/awt/event/ActionListener.html](https://docs.oracle.com/javase/7/docs/api/java/awt/event/ActionListener.html).  
You think I must create a class implements ActionListener ?

---

<div class="post-metadata">

**Author:** ![GoToLoop](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/gotoloop/32/86_2.png) [@GoToLoop](https://discourse.processing.org/u/GoToLoop)\
**Post date:** [April 6, 2019, 5:15pm UTC](https://discourse.processing.org/t/pass-a-non-final-like-a-final-arg/10029/5 "2019-04-06T17:15:32Z")

</div>

> [@Stanlepunk](#):
>
> Plus, when I try to use a temp String like that, it’s always the last String is used.

I’m assuming the String _parser_ was declared as a global field, is that so?

Now I ask, how many _parser_ fields there exist: 1 or more than 1?

The reason why `println("action event:", parser);` logs the latest value assigned to _parser_ when it’s finally called back is b/c there’s 1 _parser_ field only, not many!

Now let’s talk about workarounds on how to create many `final` closure variables to be used inside synthetic local classes, shall we?

You can simply declare a local `final` variable inside the loop in order to copy the current value of the loop’s iterator variable: `final int indexClosure = i;`

```java
for (int i = 0; i < menu_item.length; ++i) {
  final int indexClosure = i;

  menu_item[i].addActionListener(new ActionListener() { 
    @Override public void actionPerformed(final ActionEvent ae) {
      println("Action event:", info[indexClosure]);
    }
  }
  );
}

```

Or alternatively, a local `final` variable that stores the String which should be used inside the callback: `final String stringClosure = info[i];`

```java
for (int i = 0; i < menu_item.length; ++i) {
  final String stringClosure = info[i];

  menu_item[i].addActionListener(new ActionListener() { 
    @Override public void actionPerformed(final ActionEvent ae) {
      println("Action event:", stringClosure);
    }
  }
  );
}

```

Notice that in each loop iteration, a new individual `final` local variable is created to be used inside the anonymously instantiated interface. 👌

Otherwise, Java’s VM would optimize the code and would only create 1 `final` local variable for the whole loop. 💯

---

<div class="post-metadata">

**Author:** ![GoToLoop](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/gotoloop/32/86_2.png) [@GoToLoop](https://discourse.processing.org/u/GoToLoop)\
**Post date:** [April 6, 2019, 5:39pm UTC](https://discourse.processing.org/t/pass-a-non-final-like-a-final-arg/10029/6 "2019-04-06T17:39:57Z")

</div>

> [@Stanlepunk](#):
>
> Do you think I must create a `class` that `implements` ActionListener?

Well, if you intend to add more stuff to it, that’s definitely the smarter approach. 🧙

But for quick callbacks (especially functional interfaces), anonymous instantiations (or even lambdas if only the current PDE would allow them) are the preferred choice. 😉

[Docs.Oracle.com/en/java/javase/11/docs/api/java.base/java/lang/FunctionalInterface.html](http://Docs.Oracle.com/en/java/javase/11/docs/api/java.base/java/lang/FunctionalInterface.html)

---

<div class="post-metadata">

**Author:** ![Stanlepunk](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/stanlepunk/32/11509_2.png) [@Stanlepunk](https://discourse.processing.org/u/Stanlepunk)\
**Post date:** [April 7, 2019, 10:08am UTC](https://discourse.processing.org/t/pass-a-non-final-like-a-final-arg/10029/7 "2019-04-07T10:08:41Z")

</div>

Thx, that’s work perfectly! I hadn’t thought to create the variable final in the loop ☹ my mistake !
