I´m trying to map an anonymous function to a collection and I get a ClassCastException.
(defn mapanfn
[names]
(map (#(str "Hello %"))
names))
(mapanfn ["Bobby" "Nico" "Ringo"])
Thanks, R.
Just take out the extra set of parentheses around your anonymous function, and use format if you want to use a format specifier:
(defn mapanfn
[names]
(map #(format "Hello %s" %) names))
Or use str without a format specifier:
(defn mapanfn
[names]
(map #(str "Hello " %) names))
In both cases % is referring to the value your anonymous functions is called with, but it will not work inside a string.
You made a couple of mistakes here.
The first one, the % symbol should not be a part of a string. Perhaps you confused it with the standard format function. So the expression should be either (str "Hello " %) or (format "Hello %s" %).
The second one, you call your anonymous function twice because of extra parens. The #(str "Hello %") expression returns a function, but putting it into parens calls it once again and gives a string "Hello %". So inside a map function, you are trying to call a string as a function, which is calling an Exception.
The right function in your example would be just #(str "Hello " %).