First, the money may not be used “to promote or advocate the legalization or practice of prostitution and sex trafficking.” That condition was not before the court.

The question for the justices was whether the second condition, requiring recipients to have “a policy explicitly opposing prostitution and sex trafficking,” passed constitutional muster.

Chief Justice John G. Roberts Jr., writing for a six-justice majority, said the condition ran afoul of the First Amendment because it required recipients “to pledge allegiance to the government’s policy of eradicating prostitution.”

He said the groups challenging the law feared that “adopting a policy explicitly opposing prostitution may alienate certain host governments, and may diminish the effectiveness of some of their programs by making it more difficult to work with prostitutes.”

Marine Buissonniere, the director of the Open Society Public Health Program, one of the groups that challenged the condition, said the policy was counterproductive.

“Public health groups cannot tell sex workers that we ‘oppose’ them, yet expect them to be partners in preventing HIV,” she said in a statement. “Condemnation and alienation are not public health strategies.”

Roberts acknowledged that the Supreme Court’s jurisprudence on “unconstitutional conditions” was confusing. As a general matter, he said, the government has no obligation to spend money, just as recipients are not required to take the government’s money. But sometimes, he wrote, “a funding condition can result in an unconstitutional burden on First Amendment rights.”

“The line is hardly clear,” the chief justice wrote, but it is crossed when the government “seeks to leverage funding outside the contours of the program itself.”

Roberts rejected an argument by the Obama administration that the requirement to adopt a policy was needed to protect the prohibition on the use of government money to promote prostitution. Money is fungible, the administration said, and the availability of government money could free up private money to promote prostitution.

The Supreme Court accepted a similar argument in Holder v. Humanitarian Law Project, a 2010 decision that said the First Amendment did not protect benign assistance in the form of speech to groups that the government said had engaged in terrorism.

Roberts, who wrote the majority opinion in the 2010 case, said the earlier case was different because there had been evidence that “support for those organizations’ nonviolent operations was funneled to support their violent activities.”