Why isn't toString() always automatically invoked
So why isn't toString always invoked? This is an exampl开发者_C百科e using the Android API.
E.g
@Override
public void onItemSelected(AdapterView<?> adapterView, View view,
int position, long id) {
Toast.makeText(this, adapterView, Toast.LENGTH_LONG).show();
}
Will not compile. However if I change it to
@Override
public void onItemSelected(AdapterView<?> adapterView, View view,
int position, long id) {
Toast.makeText(this, adapterView.toString(), Toast.LENGTH_LONG).show();
}
It will. What is the actual difference?
adapterView
isn't a String
.
toString()
isn't invoked automatically by the compiler to perform a cast - that would undermine type safety a little. Only when there's a +""
for example, the compiler will call toString() automatically.
The only situation in which toString() is inserted by the compiler is in string concatenation.
What do you mean by always? toString()
is just a method which returns a String
representation of the object. The Toast.makeText
expects a String
parameter, but in the first case you give an object of the AdapterView
class. So it won't compile:)
also, this
@Override
public void onItemSelected(AdapterView<?> adapterView, View view,
int position, long id) {
Toast.makeText(this, "" + adapterView, Toast.LENGTH_LONG).show();
}
will compile ;)
I don't know the Android API, but AdapterView is not actually a subclass of CharSequence so you have to apply toString().
I suppose Toast.makeTest's second parameter is of type String. Then trying to pass a parameter of type AdapterView won't work. toString() is never automatically called, except when concatenating Strings (""+adapterView would work as well, but is more ugly).
The compiler decides which method is required from the name of the method and the number and types of each argument supplied. In your first example, it looks for a method called makeText which has an AdapterView as its second parameter, and finds none (your compile error would have told you that. In your second example the second parameter is a String and the compiler finds the matching method. Note that the compiler can't find the method first, then make the parameters fit, else we couldn't have overloaded methods.
精彩评论