Help understanding this syntax -- new object returned
I was reading an Android tutorial and came across this block of code:
Code :
protected Dialog onCreateDialog( int id )
{
return new AlertDialog.Builder( this )
.setTitle( "Planets" )
.setMultiChoiceItems( _options, _selections, new DialogSelectionClickHandler() )
.setPositiveButton( "OK", new DialogButtonClickHandler() )
.create();
}
Can someone explain how this works? How can you invoke the setTitle(), setMultiChoiceItems(), and other methods like this without specifying an object name. I'm sure it's correct -- I've just never seen it before.
Normally I would do something like:
Code :
protected Dialog onCreateDialog( int id )
{
Dialog d = new AlertDialog.Builder(this);
d.setTitle( "Planets" );
d.setMultiChoiceItems( _options, _selections, new DialogSelectionClickHandler() );
d.setPositiveButton( "OK", new DialogButtonClickHandler() )
d.create();
return d;
}
Does anyone know what that type of initialization used in the tutorial is called so I can read about it? I tried to look it up in a java reference book but couldn't find anything on it.
Thanks for your help.
Re: Help understanding this syntax -- new object returned
The compiler is ignoring white spaces.
Edit out the white spaces to get:
AlertDialog.Builder( this ).setTitle( "Planets" ).setMultiChoiceItems( _options, _selections, new DialogSelectionClickHandler() ).setPositiveButton( "OK", new DialogButtonClickHandler() ).create();
Each of the methods must return an object that can be used by the next method. <<<<<<<< Check this in the doc
Really ugly code. Must be generated by an IDE.
Re: Help understanding this syntax -- new object returned
You are absolutely correct. I cannot believe I didn't realize it myself. I've been away from java for a while so I assumed this was some new syntactic sugar. I agree with you that it's quite ugly, but it's not auto-generated code, it's from a book on developing android applications. Maybe this is a java convention when chaining methods?
Thanks for your help. I have a hard time moving on with stuff when I don't completely understand what's happening.
Re: Help understanding this syntax -- new object returned
Maybe with the small windows they want everything in a narrow column and with as few statements as possible. Although I think the compiler has to generate variables to hold the returned objects so I'm not sure the generated code would be any smaller.
Re: Help understanding this syntax -- new object returned
The compiler code, as I understand it, would just do...
Code :
create AlertDialog.Builder
store
call setTitle
store
call setMultiChoiceItems
store
call setPositiveButton
store
call create
store
return
On the top one anyway
The second one would be optimized down to doing the same thing, and it would be a lot prettier