Search code examples
android-studiotostringambiguous-call

Android Studio ambiguous method call for Object.toString


Others have seen the "Ambiguous Method Call" error in Android Studio for

getClass()

But I'm seeing it for

Object.toString()

Has anyone else seen that?

The version of Android Studio I have is 0.8.6.


Solution

  • First off, to answer your actual question, yes I am seeing that, and I am running Android Studio (Beta) 0.8.14, and it is an Android Studio/IntelliJ bug, as mentioned before, so your code should be fine when you actually compile. But, if you want it to stop underlining everything in red:

    As you may notice on the issue of the getClass() call found at Android Studio - Ambiguous method call getClass(), you can cast the object in question to an Object to resolve it as such:

    ((Object) myObject).toString()
    

    Alternatively, depending on the case you're dealing with, you may be able to rely on Java's included libraries implicitly* calling toString() on the object, as was the case with my code, where I was appending to a StringBuffer:

    sb.append("Object's toString() returned: " + myObject);
    

    Note: this will still work even if you didn't have the literal String object that I defined there, so this is also valid:

    sb.append(myObject);
    

    Or if you're simply printing to standard out,

    System.out.println(myObject);
    

    *As a side note, it is not actually being called implicitly, but rather many of Java's built-in classes have an overloaded method signature that accepts objects of type Object, which is then turned into a string via a call to String.valueOf(myObject) - see How an object will call toString method implicitly? for more about this.