Wednesday, July 22, 2015

NullPointerException when if-branch contains multiple statements

Consider the following code snippet:
(if true ((println "Hello") (println "World")) )
This will print the following:
Hello
World
NullPointerException   user/eval769 (NO_SOURCE_FILE:1)

The reason is (as described e.g. here), that the return value of (println "Hello") -- which is nil -- will be called as a function, with the return value of the second argument.
This can be prevented by using do:
(if true (do (println "Hello") (println "World")) )
Result:
Hello
World
nil

No comments:

Post a Comment