DIM Placement and Block Scope

Roger Garstang

Well-Known Member
Licensed User
Longtime User
Any chance we can get block level scope for variables?

Currently:

B4X:
Sub MySub
   If False Then
      Dim test as Int
   End If
End Sub

Gets converted to Java Code equivalent to:

B4X:
Sub MySub
Dim test as Int
   If False Then
      test = 0
   End If
End Sub

I looked it up a few days ago and can't remember the details now, but I think Java may still let the scope "leak" out to the Function Level, but I'd at least like the Dim to occur inside the If.

One thing that took some getting used to was how B4A didn't allow variables named the same as Globals. I think there have even been a few threads here claiming rename bugs that are actually variables or subs named the same as Globals getting their name changed. There is no case sensitivity either and I'd make a global named the same as a local without knowing it and the IDE would change all my names...which is a pain to fix when it happens. It would be really nice to be able to have locals the same name as globals and access the globals with this/me or the class name if duplicates at the local/block level.
 

Roger Garstang

Well-Known Member
Licensed User
Longtime User
Found the articles I had read earlier. Looks like Java allows Block Scope as long as the variable doesn't hide another variable with the same name within the method/sub/function. The articles mention variables in outer curly brackets above where you currently are as ones not allowed to hide, but then goes on to talk about naming the same as class variables being allowed and you access them with this.classVariable...so, it appears JAVA handles it two different ways since really Class Variables are still a curly bracket up from where you are.

I'm fine keeping the global scope and same name variables working how it is now if too difficult to get a solution handling scope like JAVA does, but I'd still like to at least get the DIM occurring where I place it in code.
 
Last edited:
Upvote 0
Top