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.
according to this it sounds like the inspection for final attribute of val was an intellij feature that still need to be implemented.
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
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?
I just filed a issue IDEA-153706 for Intellij.
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)
Most helpful comment
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)