Reputation: 650
I'm getting this weird NPE in my clojure hello world
(ns test-app.core
(:gen-class))
(defn -main [& args]
( (println "Hello")) )
Notice the extra () around the (println "Hello"). That seems to be the problem, if i remove that its just fine.
And the output of the program. Notice that the code actually printed "Hello" and the threw.
Hello
Exception in thread "main" java.lang.NullPointerException
at test_app.core$_main.doInvoke(core.clj:5)
at clojure.lang.RestFn.invoke(RestFn.java:397)
at clojure.lang.Var.invoke(Var.java:411)
at user$eval5$fn__7.invoke(form-init9064825970813284041.clj:1)
at user$eval5.invoke(form-init9064825970813284041.clj:1)
at clojure.lang.Compiler.eval(Compiler.java:6619)
at clojure.lang.Compiler.eval(Compiler.java:6609)
at clojure.lang.Compiler.load(Compiler.java:7064)
at clojure.lang.Compiler.loadFile(Compiler.java:7020)
at clojure.main$load_script.invoke(main.clj:294)
at clojure.main$init_opt.invoke(main.clj:299)
at clojure.main$initialize.invoke(main.clj:327)
at clojure.main$null_opt.invoke(main.clj:362)
at clojure.main$main.doInvoke(main.clj:440)
at clojure.lang.RestFn.invoke(RestFn.java:421)
at clojure.lang.Var.invoke(Var.java:419)
at clojure.lang.AFn.applyToHelper(AFn.java:163)
at clojure.lang.Var.applyTo(Var.java:532)
at clojure.main.main(main.java:37)
[Finished in 4.0s with exit code 1]
My question is why is this happening?
Or better: So is this a bug in or is it expected behaviour?
I assume that's because the first arg of a list should be the name of a function, and here its another list :P. but shouldn't the complier/runtime give a nicer error in that case?
Thx in advance.
Upvotes: 3
Views: 274
Reputation: 13951
I assume that's because the first arg of a list should be the name of a function, and here its another list
Close - when code is evaluated, the first item in the list form is evaluated, and the result is invoked as a function (the first item could be the name of a function, or another function call that returns a function). In this case, the println
function always returns nil
; attempting to invoke nil
as a function yields the NPE that you see.
shouldn't the complier/runtime give a nicer error in that case?
Not necessarily - the compiler can't know ahead of time whether the result of evaluating the inner function call will be a valid function to use for the outer function call. The following works just fine:
((partial + 1) 2)
because partial
returns another function.
Upvotes: 5