6

As per the docs, it's not possible to declare a variable inside an inner scope, if the variable already exists in the outer scope, see below:

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_variables.htm

Variables can be defined at any point in a block, and take on scope from that point forward. Sub-blocks can’t redefine a variable name that has already been used in a parent block, but parallel blocks can reuse a variable name. For example:

Integer i; { // Integer i; This declaration is not allowed }

However, this code runs just fine in the developer console:

String name = 'world';

if(true){
    String name = 'hello';
    System.debug('inside the scope of it: '+name);
}

System.debug('outside the scope of if: '+name);

{
    String name = 'static';
    System.debug('inside the static init: '+name);
}

And results in the following:

(11981838)|USER_DEBUG|[5]|DEBUG|inside the scope of it: hello
(12032678)|USER_DEBUG|[8]|DEBUG|outside the scope of if: world
(12094224)|USER_DEBUG|[12]|DEBUG|static: static

So, is the documentation wrong? or am I'm not understanding the example provided by the docs?

EDIT

Adding more info based on the answer provided: it appears that the "global" scope (i.e instance variables) can be duplicated in inner scopes (methods), for example this compiles:

    public class Scope {
    
        String name;
    
        public void hi(){
            String name;
       }
   }

But the following doesn't, because the variable is duplicated inside the if block

public class Scope {

    String name;

    public void hi(){
        String name;
    
        if(true){
            String name;
        }
    }

}

1 Answer 1

5

This will not compile if you try to save in normal method in a class.

enter image description here

But if you try in Anonymous Window it is running. However only below lines will fail:

String name = 'world';
String name = 'w2';

I guess anonymous window treats each block of code separately.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .