When you play your last tile the tiles in your opponent's rack are added up, subtracted from your opponent's score, and added to your score.
If your opponent plays his/her last tile first, then the tiles in your rack are added up, subtracted from your score, and added to your opponent's score.
So let's say that you're up 400-385 and you have the letter C remaining to play. Your opponent plays his last tiles for 8 points giving him 393. The 4 points for the C are subtracted from your score giving you 396 points. Those 4 points are added to your opponent's score giving him 397 points and the win.
Also if you resign at any point, regardless of the score, you always lose.