Technically yes, though obviously it only works if your opponent leads with a Legendary into Ditto (instead of switching to something weak) despite being able to see that Ditto is the next battle. On top of that, it will be significantly less bulky than an actual Legendary because Ditto retains its level, HP and IVs. https://pokemongo.gamepress.gg/ditto-mechanics
So, I read that if you use a Ditto in a Legendary raid, it will transform into said Legendary.
But what happens if a defening Ditto encounters a Legendary as itts first opponent? Would it be a way to introduce legendaries in gym defense?