2 Samuel 8:18 says: "...and David's sons were priests."
How could David's sons be priests if he was a Judahite and priests were Levites?
Excellent question. Let's explore some explanations.
1) The first explanation is simply that they were indeed unlawful priests (c.f. Judges 17).
2) That the text would mention this transgression without consequence seems strange to many commentators who propose a second explanation - that the word "priest" here means "advisor". Let's examine a textual basis for this claim:
Samuel II 20:25-26
This is strange wording because all three priests should have been mentioned in one breath. Moreover, what does it mean that the first two were "priests" while the latter was "David's priest" (the job is not a personal one)?
Targum Jonathan indeed translates the first use as regular "priests" but the second use as "chief". So too many commentators explain that he was an advisor to the king. Indeed most of these commentators use the same explanation for David's sons. Targum Jonathan there too translates as "chiefs".
This sits well with Chronicles I 18:17, which is a match for our verse, although reads
A clause in Isaiah 61:10 reads כחתן יכהן פאר which uses the same word "priest" as a verb, but is explained by some commentators there (see Metzudot) to simply mean "make grand". Again, the root "priest" is used as a term of grandeur and position, rather than specifically tribal priest.
3) A third explanation is that they were in charge of the priests. This resolves the conflict and has a textual basis. Our verse in Samuel II 8:18 verse reads
The first clause is translated as "and Benaiah the son of Jehoiada was over both the Cherethites and the Pelethites;" The term "over" isn't mentioned in the Hebrew, but is implied by the context - all previous verses in this chapter mention that Mr. X was over (i.e. in charge of) Y. So the second clause can be read in the same way - and David's sons were over the priests. I.e. They were administrators. Managerial staff for the priestly office.
This textual understanding is due to Prof. Yehuda Elitzur.
4) There are other explanations that I don't think warrant much explanation, although I'll mention them in passing. For example, that similar to Judges 17, at first they were indeed unlawful priests, and then later they were replaced by real priests and became government officials (that settles the difference between Chronicles and Samuel, they discussed different time periods). Another explanation is that they were priests in only part of the sense of the word. Not that they performed priestly duties, but that they were judges and legal adjudicators as per Deuteronomy 17.