簡體   English   中英

Clojure中-toString與.toString的區別

[英]The difference between -toString vs .toString in Clojure

在關於:gen-class Anatomy的gen-class的解釋之后,我使用leiningen來獲取類文件。

  1. leon new pinger創建一個項目。
  2. cd srcmkdir some並在mkdir some創建了一個Example.clj文件。
  3. 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會在示例中引發錯誤?

首先,一些術語:

  1. (.toString (some.Example.))是對新構造的some.Example實例的toString方法的調用。

  2. (-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,或者使用referuserequirealias來使用更短的名稱引用它:

(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沒有首先使用referuse或者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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM