Closeable lazy-seq in Clojure

Viewed 69

I'm trying to create a lazy-seq which is also closeable. What would be the cleanest way to do that in Clojure? Intended usage (but it's just one example, I can think of more usages for a closeable lazy sequance):

(with-open [lines (file-lines-seq file)]
   (consume (map do-stuff-to-line lines))) 

Which in this case would be equivalent to:

(with-open [reader io/reader file]
    (consume (map do-stuff-to-line (line-seq file))))
1 Answers

Managed to get the intended usage with this wonderful piece of code:

(defn file-lines-seq [file]
  (let [reader (clojure.java.io/reader file)
        lines-seq (line-seq reader)]
    (reify
      Closeable
      (close [this] (.close reader))
      
      ISeq
      (first [this] (.first lines-seq))
      (next [this] (.next lines-seq))
      (more [this] (.more lines-seq))
      (cons [this var1] (.cons lines-seq var1))
      (count [this] (.count lines-seq))
      (empty [this] (.empty lines-seq))
      (equiv [this var1] (.equiv lines-seq var1))
      (seq [this] (.seq lines-seq))
)))

If there's a less ugly way to do this, please let me know.

Related