Support accessing instance variables & self from the outside of a block or closure #57

Open
spencergibb opened this Issue Mar 23, 2011 · 1 comment

Projects

None yet

3 participants

@spencergibb

see issue #0 here http://groups.google.com/group/mirah/browse_thread/thread/9037d2ac8db02e47/591fd73142139862

and here
http://groups.google.com/group/mirah/browse_thread/thread/595ff2dae2dc2fc2

eg:

class Foo 
def bar 
@a = 10 
Thread.new { puts @a }.start 
end 
end 
Foo.new.bar 
Inference Error: 
foo.mirah:4: Unable to infer type. 
Thread.new{ puts @a }.start 
^^^ 
@stapelberg

Yes, please. This one is quite important when developing for android, due to the following effect:

class Start < ListActivity
  def onCreate(state)
    super state

    setContentView(R.layout.main)

    getListView().setOnItemClickListener do |parent, view, pos, id|
      intent = Intent.new(self, PlayGame.class)
      startActivity(intent)
    end
  end

This code does not work, startActivity being a method of Activity is the problem (and the missing access to self). You can use the following workaround:

class Start < ListActivity
  def onCreate(state)
    super state

    setContentView(R.layout.main)

    # store a reference to 'self' to use it inside the listener
    activity = self

    getListView().setOnItemClickListener do |parent, view, pos, id|
      intent = Intent.new(activity, PlayGame.class)
      activity.startActivity(intent)
    end
  end

In normal java, the following code works:

void onCreate(Bundle state) {
    super.onCreate(state);

    setContentView(R.layout.main);

    getListView().setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView parent, View view, int position, long id) {
            startActivity(new Intent(Start.this, PlayGame.class));
        });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment