Skip to content
This repository has been archived by the owner on Nov 3, 2024. It is now read-only.

val causes intellij to show an invalid error when used alongside an anonymous class #158

Closed
mr opened this issue Nov 24, 2015 · 5 comments
Closed
Assignees
Milestone

Comments

@mr
Copy link

mr commented Nov 24, 2015

val is supposed to infer the type of a value and make it final, so you should be able to use them in anonymous classes. In fact you can do this! Intellij doesn't believe you though:

public class ValTest {
    public void doSomething() {
        val foo = new Foo();
        val bar = new Bar();
        foo.setBazListener(new BazListener () {
            @Override
            public Bar onBaz() {
                return bar;
            }
        });
    }
}

When using this code there is an error on bar in return bar that says "Variable bar is accessed from within inner class, needs to be declared final". I agree, however val indeed does make it final. This code actually compiles and runs fine. I'm currently using android studio 1.2.1.1, and I think it's based off of idea 14.

@jimmec
Copy link

jimmec commented Jan 3, 2016

according to this it sounds like the inspection for final attribute of val was an intellij feature that still need to be implemented.

@mplushnikov
Copy link
Owner

Yes, it is not possible to change visibility of existing elements in Intellij at the moment. Thats why val is non final for Intellij.
Similar issue #137

@alexejk
Copy link
Collaborator

alexejk commented Mar 26, 2016

I've just tested the provided example with latest version of the plugin and it would seem to have solved the issue? Specifically i get no inspection errors in this code sample:

public class Test {

    public void doSomething() {
        val foo = new Foo();
        val bar = new Bar();
        foo.setBazListener(new BazListener () {
            @Override
            public Bar onBaz() {
                return bar;
            }
        });
    }

    public class Foo {
        public void setBazListener(BazListener listener){
        };
    }

    public interface BazListener {
        public Bar onBaz();
    }

    public class Bar {}
}

Difference is, however, that the inspection now says "requires it to be final or effectively final", which it is in current sample. By adding additional bar = new Bar(); just before foo.setBazListener call you can trigger the inspection error claiming bar is not final.

IS there an IDEA issue tracker link for new extension point to mark variables as final?

@mplushnikov
Copy link
Owner

I just filed a issue IDEA-153706 for Intellij.

@mplushnikov
Copy link
Owner

The update should be available in the next version of plugin (0.12) and will work only for new versions of IntelliJ Idea (2016.2)(build >=146.1154)

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants