I typically think of this as a unique advantage that programmers have. In almost every other industry I see, I see people who never get the chance to focus all their attention on intellectually challenging tasks for hours without break, and a lot of them seem super distracted and like their brain have been negatively affected by this absence. But programmers seem like the rare species that actually do get this privilege, and this is usually the reason I prefer intellectual conversations with coders than almost anyone else (even when the topic is something other than engineering).
I agree with you. But lately I've been noticing myself being distracted a lot and finding it hard to concentrate... for example I have a hard problem in front of me and in the momment something goes wrong I just switch task and go on hn/reddit/mail etc...
Habituating myself with music and special rooms that I'm very strict about associating only to work (never play) has been the key for me. Play music when you work, and be very strict about not playing the same track/genre when you go on hn/reddit. Sometimes I stand up when people speak to me, just so I don't encourage my mind to allow "conversation thoughts" to bubble up from my subconsious when I'm in a chair. If you're strict about this, and you do it for long enough, it becomes much easier. (Don't be too hard on yourself when you fail, let it take the time it needs to take, be patient. And be careful once you've reached the good habit state. Remember how fragile it is and how much effort was required to get to that point.)