speedywhy
speedywhy

Reputation: 69

Clojure clojure.string/split hit java.lang.ClassCastException: clojure.lang.LazySeq cannot be cast to java.lang.CharSequence

I tried to write a function to process a line of string by calling str\split, the function works fine if i call it directly in LEIN REPL window, but will hit the above call error while trying to run the program from LEIN RUN. Any suggestion?

(let [num-letters (count (apply str line))
      num-spaces-needed (- column-length num-letters)
      num-words (count  (clojure.string/split line #"\s"))
      num-space-in-group (if (= 1 num-words) num-spaces-needed (/ num-spaces-needed (- num-words 1)))
      group-of-spaces (repeat num-space-in-group " ")
      padding (create-list-spaces num-spaces-needed (dec (count line)))]
  (   clojure.string/join "" (if (empty? padding) (cons line group-of-spaces) 
                (cons (first line) (interleave (rest line) padding)))))

Upvotes: 0

Views: 300

Answers (1)

Toni Vanhala
Toni Vanhala

Reputation: 1372

I suppose you pass line as a parameter to your function, although it was omitted from your code snippet.

You should check for differences in the line parameter, when calling the function from these two different entry points. First, let's name your function as tokenize for convenience. Now, the vanilla app template in Leiningen creates a -main that looks similar to this, after I add the tokenize call:

(defn -main
  [& args]
  (tokenize args))

The arguments are destructured with the rest operator &, which builds a Seq of the arguments (args). So, when running this with lein run I want this to work!, you end up invoking the tokenize function with a sequence. clojure.string/split cannot be applied to a sequence, and you get a stack trace.

However, when you call your function from lein repl, a natural way to do it is with a spell like (tokenize "Iä! Iä! Cthulhu fhtang!"). This will work, as your call parameter is now just a string, not a sequence.

In the end, it comes down to how you call your function. A more confident answer would require details on that, as @sam-estep commented.

Upvotes: 1

Related Questions