带有休息参数的匿名函数抛出NullPointerException [英] Anonymous function with rest parameter throwing NullPointerException
本文介绍了带有休息参数的匿名函数抛出NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是函数
(#(
(println (str "first: " %1))
(println (str "second: " %2))
(println (str "rest: " (clojure.string/join ", " %&))))
"f" "s" "x" "y" "z")
在苹果酒中运行时我得到了预期的结果,但是最后我看到我也得到了NullPointerException。
When running this in cider I get the desired result but at the end I see that I am also getting a NullPointerException.
这种形式的匿名函数似乎与
It seems that this form of anonymous function has some issues with destructuring.
因为,当我尝试以下形式的匿名函数时,它起作用。
Because, when I try the following form of anonymous function, it works.
((fn [f s & rest]
(println (str "first: " f))
(println (str "second: " s))
(println (str (clojure.string/join ", " rest))))
"f" "s" "x" "y" "z")
有人可以解释为什么会这样吗?
Can someone explain why is this happening ?
推荐答案
您需要做
:
(#(do
(println (str "first: " %1))
(println (str "second: " %2))
(println (str "rest: " (clojure.string/join ", " %&))))
"f" "s" "x" "y" "z")
没有 do
,您正在尝试调用第一个 println
的结果,(即在列表的其余元素上 nil
)。 fn
具有隐式 do
。
Without the do
, you're trying to invoke the result of the first println
, (i.e. nil
) on the remaining elements of the list. fn
has an implicit do
.
情况下,比较((println))
和(do(println))
这篇关于带有休息参数的匿名函数抛出NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文