Clojure.core.set throws ClassCastException

How can (set) throw a ClassCastException?

ClassCastException
class clojure.lang.PersistentHashMap cannot be cast to class java.util.Map$Entry (clojure.lang.PersistentHashMap is in unnamed module of loader 'app'; java.util.Map$Entry is in module java.base of loader 'bootstrap')

Code:

(->> (data/diff foo bar)
     (take 2)
     (mapcat keys)
     (set))

Stacktrace points to the line where (set) is called:

`clojure.lang.APersistentMap$KeySeq` in `first`
`clojure.lang.RT` in `first` at line `692`
`clojure.core$first__5449` in `invokeStatic` at line `55`
`clojure.core$reduce1` in `invokeStatic` at line `946`
`clojure.core$set` in `invokeStatic` at line `4115`
`clojure.core$set` in `invoke` at line `4107`

Clojure version:

[org.clojure/clojure "1.11.2"]

This was answered on Slack: Slack

TL;DR: keys expects a sequence of MapEntry pairs but data/diff produces a sequence of data for which that cannot apply. The set call is irrelevant here – it just happens to realize the result of mapcat. A slightly different example that produces a similar error:

user=> (->> (clojure.data/diff #{1} #{2}) (take 2) (mapcat keys))
Error printing return value (ClassCastException) at clojure.lang.APersistentMap$KeySeq/first (APersistentMap.java:171).
class java.lang.Long cannot be cast to class java.util.Map$Entry (java.lang.Long and java.util.Map$Entry are in module java.base of loader 'bootstrap')

(You don’t say what foo and bar are here)