Search code examples
clojure

How to write a function's result use function spit?


I have this code:

(defn a[]
  1
  )

(defn test []
  (spit "test.txt" a))

when run test,the test.txt only have the object's name:

test$a@603494de

but I want it have the value 1

or if I use with-open:

(defn test1 []
  (with-open [w (clojure.java.io/writer "test.txt")]
    (.write w a)))

got error:IllegalArgumentException No matching method found: write for class java.io.BufferedWriter

but if I write:

(.write w "a")

there is no error

how to fix it?Thanks!


Solution

  • Two things are happening:

    First, a is a function. You need to either call it and get the value, or use def instead (since its constant):

    (def a 1) ;; no need to call a
    (defn a[] 1) ;; need to call a: (a)
    

    Second, (assuming you kept defn and a is still a function), to create a string as an argument for spit you need to use str:

    (spit "test.txt" (str (a))) ;; note a is called