当 defrecord 和协议都在另一个命名空间中时扩展协议

extend-protocol when both defrecord and protocol are in another namespace

我正在尝试使用 extend-protocol 来扩展来自不同名称空间的协议和记录,但出现以下错误:

Syntax error compiling at (src/http_client/client_mixed.clj:10:1).
No such var: either/Right

代码如下:

(ns http-client.client-mixed
  (:require [cats.core :as m]
            [cats.monad.either :as either]
            [fmnoise.flow :as f]))

(extend-protocol f/Flow
  either/Right
  (?ok [this f] (f (m/extract this)))
  (?err [this _] (m/extract this))
  (?throw [this] (m/extract this))

  either/Left
  (?ok [this _] (m/extract this))
  (?err [this f] (f (ex-info "Either.Left" (m/extract this))))
  (?throw [this] (throw (ex-info "Either.Left" (m/extract this)))))

defrecord 必须作为常规 Java class 导入。所以,这将是正确的代码:

(ns http-client.client-mixed
  (:require [cats.core :as m]
            [cats.monad.either :as either]
            [fmnoise.flow :as f])
  (:import (cats.monad.either Left Right)))

(extend-protocol f/Flow
  Right
  (?ok [this f] (f (m/extract this)))
  (?err [this _] (m/extract this))
  (?throw [this] (m/extract this))

  Left
  (?ok [this _] (m/extract this))
  (?err [this f] (f (ex-info "Either.Left" (m/extract this))))
  (?throw [this] (throw (ex-info "Either.Left" (m/extract this)))))