Monday, January 25, 2016

Compile Error: Incompatible key type Datetime for Map<String,List<Event>> at line

You will receive this type of error commonly when your working with collections or while doing at variable assignments .This error basically comes whenever your passing incorrect key datatype to maps.

1:  List<Event> eventRec= [Select StartDateTime,EndDateTime from Event limit 10];  
2:  Map<String,List<Event>> mapEvents = new Map<String,List<Event>>();  
3:  mapEvents.put( eventRec[1].StartDateTime,eventRec);  

In the above code snippet you will an error like Compile Error: Incompatible key type Datetime for Map&lt;String,List&lt;Event&gt;&gt; at line 3 column 1 because the mapEvents map key datatype is String but we are passing Datetime (eventRec.StartDateTime) type parameter. 

Wok Around Solution
Pass the correct key value datatype based on your map declaration.In our we need to pass so modified code as below
1:  List<Event> eventRec= [Select StartDateTime,EndDateTime from Event limit 10];  
2:  Map<String,List<Event>> mapEvents = new Map<String,List<Event>>();  
3:  mapEvents.put( String.valueOf(eventRec[1].StartDateTime),eventRec);  

Enjoy..........!!

No comments:

Post a Comment