0

Downcasting used to look like this:

((TextView)rootView.findViewById(R.id.fooText)).setText("Foo");

Today I noticed that Android Studio uses a different syntax instead:

rootView.<TextView>findViewById(R.id.fooText).setText("Foo");

Is this a new syntax to replace the old one? Does it have a name? What are its advantages?

AndreKR
  • 32,613
  • 18
  • 106
  • 168
  • 2
    The second syntax isn't casting. Its using a generic argument in the method call. See https://stackoverflow.com/questions/3012781/java-syntax-for-explicitly-specifying-generic-arguments-in-method-calls/47266244 – OH GOD SPIDERS Jul 14 '21 at 16:30
  • The advantages of the second method are pretty much the same as for generics vs casting in general: You will have compile time checks that will tell you is the generic type you are using is valid for the method or if the method supports generics at all. With casting you'll only ever know during runtime whether it works as intended or might result in an exception – OH GOD SPIDERS Jul 14 '21 at 16:33

1 Answers1

1

That's not a cast. Java's cast syntax is, and always has been, preceding the value with a parenthesized type. findViewById has signature

public <T> T findViewById (int id)

i.e. you can specify the return type T as part of the generic type of findViewById. Really, all that that does is force findViewbyId to do the traditional (T) cast for you (which is equally unsafe and still a downcast internally). In standard Java, there's really no reason to do that as opposed to an explicit cast. However,

Note: In most cases -- depending on compiler support -- the resulting view is automatically cast to the target class type. If the target class type is unconstrained, an explicit cast may be necessary.

So it sounds like some IDEs, probably Android Studio, have special inference rules that can infer (or validate) the type of T in certain cases.

Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116