简体   繁体   English

在多个名称空间中使用记录

[英]Use record in several namespaces

I have clojure file with some predefined functions and records 我有一些预定义功能和记录的clojure文件

;outer.clj
(ns outer )
(defn foo [a] (println a))
(defrecord M [id])

And now usage file 现在使用文件

;inner.clj
(ns inner (:use outer ))
(foo 2)    ;works fine
(println (:id (M. 4))) ;throws IllegalArgumentException: Unable to resolve classname: M

Why does function imports fine but records definition doesn't? 为什么函数可以很好地导入但记录定义却不能呢? How I should import it? 我应该如何导入?

Because defrecord generates a JVM class 'under the covers' you need to import that class... 因为defrecord在幕后生成了一个JVM类,所以您需要导入该类...

;inner.clj
(ns inner 
    (:use outer )
    (:import outer.M)
(foo 2)    ;works fine
(println (:id (M. 4))) ; works with import

While sw1nn is correct, since 1.3 you needn't go through a separate import. 尽管sw1nn是正确的,但从1.3开始,您无需进行单独的导入。 Both defrecord and deftype also create constructor functions, which would be available via use / require just like any other function. defrecorddeftype可以创建构造函数,就像其他函数一样,可以通过use / require

The function created by both follows the form ->MyType and takes positional args. 两者创建的函数均采用->MyType形式->MyType->MyType位置参数。

Additionally, defrecord creates a second constructor function that takes a map arg, map->MyRecord . 此外, defrecord创建了第二个构造函数,该函数接受一个映射arg map->MyRecord

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM