Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected behaviour from clojure.java.api.Clojure

I've been experimenting with clojure.java.api introduced in Clojure 1.6.0, as I'd like to import some Clojure functionality into my java project. Unfortunately, it is not behaving as I'd expect when I invoke the conditional functions and and or from Java.

IFn and = Clojure.var("clojure.core", "and");
IFn or = Clojure.var("clojure.core", "or");

-- equivalent to (and true false) in clojure
and.invoke(true,false); --> returns true rather than false???   

-- equivalent to (or true false) in clojure
or.invoke(true,false); --> returns null rather than true???

-- equivalent to (and true true) in clojure
and.invoke(true,true); --> returns true as expected

-- equivalent to (or true true) in clojure    
or.invoke(true,true); --> returns null rather than true???

I can't believe this is a bug, so I suspect I'm missing something fairly fundamental relating to the API. Whatever the cause, it has left me rather confused. If anyone can offer an explanation I'd be very grateful.

Thanks,

Matt.

like image 568
Matthew Gretton Avatar asked Mar 25 '26 07:03

Matthew Gretton


1 Answers

and and or are macros and the rules for evaluation are somewhat different for them. For example, when on the Clojure REPL, trying to evaluate and throws CompilerException java.lang.RuntimeException: Can't take value of a macro: #'clojure.core/and, compiling:(NO_SOURCE_PATH:0:0).

There should be a way to use them through clojure.java.api.Clojure though, but I haven't figured it out for now since macros need to be compiled in order to work.

The next best option I can think of is using eval but I'm not sure that is something you want to do. On the other hand, why use and/or when the good old &&/|| Java operators exist?

like image 74
juan.facorro Avatar answered Mar 27 '26 21:03

juan.facorro