Cannot refer to a non-final variable tokens inside an inner class defined in a different method

dr4913
Compilation Error - Cannot refer to a non-final variable tokens inside an inner class defined in a different method
Java Compiler - 1.7
Eclipse - Kepler

I am getting compilation error for below code taken from provided Examples.java. The suggested fix is to use final keyword for tokens variable. Please let me know if its fine to continue using final keyword.

public void tickerUsage(KiteConnect kiteConnect, ArrayList tokens) throws IOException, WebSocketException, KiteException
{
/** To get live price use websocket connection.
* It is recommended to use only one websocket connection at any point of time and make sure you stop connection, once user goes out of app.
* custom url points to new endpoint which can be used till complete Kite Connect 3 migration is done. */
final KiteTicker tickerProvider = new KiteTicker(kiteConnect.getAccessToken(), kiteConnect.getApiKey());

tickerProvider.setOnConnectedListener(new OnConnect()
{
@Override
public void onConnected()
{
/** Subscribe ticks for token.
* By default, all tokens are subscribed for modeQuote.
* */

tickerProvider.subscribe(tokens);
tickerProvider.setMode(tokens, KiteTicker.modeFull);
  • sujith
    Can you let us know which line exactly is throwing the error?
  • dr4913
    tickerProvider.subscribe(tokens);
    tickerProvider.setMode(tokens, KiteTicker.modeFull);
    Above 2 lines are throwing the error.
  • sujith
    You can declare it as final. AFAIK there won't be any issue. If you still feel it is not thread safe then you may try to make it a global variable.
Sign In or Register to comment.