LVTI and wildcards

First, let's talk about LVTI and wildcards (?). It is a common practice to associate wildcards with Class and write something like this:

// explicit type
Class<?> clazz = Long.class;

In such cases, there is no problem with using var instead of Class<?>. Depending on the right-hand side type, the compiler will infer the correct type. In this example, the compiler will infer Class<Long>.

But notice that replacing wildcards with LVTI should be done carefully and that you should be aware of the consequences (or side effects). Let's look at an example where replacing a wildcard with var is a bad choice. Consider the following piece of code:

Collection<?> stuff = new ArrayList<>();
stuff.add("hello"); // compile time error
stuff.add("world"); // compile time error

This code doesn't compile because of incompatible types. A very bad approach would be to fix this code by replacing the wildcard with var, as follows:

var stuff = new ArrayList<>();
strings.add("hello"); // no error
strings.add("world"); // no error

By using var, the error will disappear, but this is not what we had in mind when we wrote the preceding code (the code with type incompatibility errors). So, as a rule of thumb, don't replace Foo<?> with var just because some annoying errors will disappear by magic! Try to think about what the intended task was and act accordingly. For example, maybe in the preceding snippet of code, we tried to define ArrayList<String> and, by mistake, ended up with Collection<?>.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.59.219