3

I'm a newbie to APEX but not the platform. Yes I'm going through the trailhead Apex Basics & Database and on the SOSL module I think I have this correct but I'm getting this List to List error: Invalid conversion from runtime type List to List.

Since this is what I think a very simple example, ie no type casting is required from what I've seen in other posts. The screen shot has my code and the error of what it's saying: screenshot.

public class ContactAndLeadSearch {

    public static List<List<sObject>> searchContactsAndLeads(String findMe){

        List<List<sObject>> myList = [FIND :findMe IN Name FIELDS 
           RETURNING Lead(Name),Contact(Name)];
        Contact[] searchContact = (Contact[])myList[0];
        Lead[] searchLead = (Lead[])myList[1];

        return myList;
    }
}

1 Answer 1

3

The lists are returned in the order you specify. So if you wanted to cast them for some reason, the List<Lead> would come first, and the List<Contact> will come second. Your code fails at runtime because you try to convert your first list (of type List<Lead>) to a List<Contact>, and vice versa. Simply swap indices and you will be fine. The following will not throw a runtime exception.

public static List<List<sObject>> searchContactsAndLeads(String findMe){

    List<List<sObject>> myList = [FIND :findMe IN Name FIELDS 
                                  RETURNING Lead(Name),Contact(Name)];
    Contact[] searchContact = (Contact[])myList[1];
    Lead[] searchLead = (Lead[])myList[0];

    return myList;
}

However, you don't really need to do any casting at all, or even cache the list, so you could simplify to just:

public static List<List<sObject>> searchContactsAndLeads(String findMe)
{
    return [FIND :findMe IN Name FIELDS RETURNING Lead(Name),Contact(Name)];
}
5
  • FWIW, the casts aren't actually necessary; you can always assign an SObject[] directly to a concrete type.
    – sfdcfox
    Commented Nov 2, 2016 at 17:03
  • 1
    True but the type ordering is still the core problem here.
    – Adrian Larson
    Commented Nov 2, 2016 at 17:05
  • Of course. I'd prefer the last bit of code in code I'd write that returned a SOSL result like this.
    – sfdcfox
    Commented Nov 2, 2016 at 17:07
  • Certainly no need for further manipulation in this case.
    – Adrian Larson
    Commented Nov 2, 2016 at 17:08
  • Ah - makes sense... I get that now, thanks. You're right no casting was required, I was just copying the code and screwed up some of my renaming, which then produced that error.
    – Fifedog
    Commented Nov 3, 2016 at 15:20

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .