Skip to content

Instantly share code, notes, and snippets.

@pyricau
Last active December 10, 2015 05:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pyricau/4389643 to your computer and use it in GitHub Desktop.
Save pyricau/4389643 to your computer and use it in GitHub Desktop.

Current implementation of findViewById() :

public class View {

    public final View findViewById(int id) {
        if (id < 0) {
            return null;
        }
        return findViewTraversal(id);
    }

}

Ideal implementation with generic return type, leveraging the super powers of the java compiler:

public class View {

    public final <T extends View> T findViewById(int id) {
        if (id < 0) {
            return null;
        }
        return (T) findViewTraversal(id);
    }

}

The advantage would be that instead of:

TextView textView = (TextView) myView.findViewById(R.id.text);

One could write:

TextView textView = myView.findViewById(R.id.text);

This means noise reduction: getting rid of the unecessary cast.

Would such a change break Android backward compatibility? Discuss.

@JoanZapata
Copy link

That's brilliant.
Moreover I can't find any backward compatibility issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment