[英]The difference between -toString vs .toString in Clojure
在關於:gen-class
Anatomy的gen-class
的解釋之后,我使用leiningen
來獲取類文件。
leon new pinger
創建一個項目。 cd src
和mkdir some
並在mkdir some
創建了一個Example.clj
文件。 project.clj
添加了:aot [some.Example]
(或:aot :all
)。 Example.clj如下:
(ns some.Example
(:gen-class))
(defn -toString
[this]
"Hello, World!")
然后我執行lein compile
以獲取target
目錄中的類。
然后,我用lein repl
執行這段代碼。
(-toString (some.Example.)) ; should return "Hello, World!"
但是,我收到此錯誤消息。
CompilerException java.lang.RuntimeException: Unable to resolve symbol:
-toString in this context, compiling:(/private/var/folders/nw/dmb7jh3d2hq89296z2gnntqm0000gn/T/form-
init7145760420048735997.clj:1:1)
.toString
工作正常。
user=> (.toString (some.Example.))
"Hello, World!"
該網站解釋說我應該從-toString
和.toString
獲得相同的結果,但我只得到.toString
正確結果。
Clojure中-toString
和.toString
什么區別? 為什么-toString
會在示例中引發錯誤?
首先,一些術語:
(.toString (some.Example.))
是對新構造的some.Example
實例的toString
方法的調用。
(-toString (some.Example.))
是一個常規的Clojure函數調用, -toString
是存儲函數的Clojure Var的名稱,而(some.Example.)
是它的唯一參數。
:gen-class
排列事物,以便-toString
Var支持toString
方法; 也就是說,對some.Example
實例的toString
方法的任何調用some.Example
導致對-toString
的調用。 所以確實只是直接調用-toString
是等效的。
但是,在通過引用存儲它的Var來調用Clojure函數之前,需要確保已經加載了這個Var所在的命名空間(這里沒有問題,因為你能夠構造一個實例) some.Example
)然后通過其完全限定名稱引用Var,或者使用refer
, use
, require
或alias
來使用更短的名稱引用它:
(some.Example/-toString ...)
(use '[some.Example :only [-toString]])
(-toString ...)
(require '[some.Example :refer [-toString]])
(-toString ...)
(require '[some.Example :as se])
(se/-toString ...)
;; refer and alias are typically not used directly
如果你說-toString
沒有首先使用refer
, use
或者require
如上所示1 ,Clojure將嘗試將符號-toString
解析為當前命名空間中的Var(通常是REPL會話中的user
;使用lein repl
它可能是:main
您的defproject
表單中的命名空間)。
1這是關於REPL的。 在源文件中,您通常在ns
表單中使用:use
或:require
; 語法與use
/ require
減去引用相同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.