2

So why isn't toString always invoked? This is an example 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?

Akram
  • 7,548
  • 8
  • 45
  • 72
whirlwin
  • 16,044
  • 17
  • 67
  • 98

7 Answers7

8

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.

davin
  • 44,863
  • 9
  • 78
  • 78
6

The only situation in which toString() is inserted by the compiler is in string concatenation.

Peter Taylor
  • 4,918
  • 1
  • 34
  • 59
5

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:)

Petar Minchev
  • 46,889
  • 11
  • 103
  • 119
  • Thanks. I usually use System.err to debug my code, and forgot it is capable of handling more than just strings. :) – whirlwin Jan 16 '11 at 13:55
1

also, this

@Override
public void onItemSelected(AdapterView<?> adapterView, View view,
            int position, long id) {
    Toast.makeText(this, "" + adapterView, Toast.LENGTH_LONG).show();
}

will compile ;)

davogotland
  • 2,718
  • 1
  • 15
  • 19
0

I don't know the Android API, but AdapterView is not actually a subclass of CharSequence so you have to apply toString().

PeterMmm
  • 24,152
  • 13
  • 73
  • 111
0

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).

Herman
  • 1
0

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.

Highland Mark
  • 1,002
  • 1
  • 7
  • 12