Amogh Talpallikar
Amogh Talpallikar

Reputation: 12184

Why do we see Arity related exceptions at runtime in Clojure?

Why do we see Arity related exceptions at runtime in Clojure?

I suppose, this is something that a compiler should be able to check when we compile the code itself. What is the reason that we only catch such errors at runtime. ?

Upvotes: 4

Views: 510

Answers (2)

amalloy
amalloy

Reputation: 92117

Clojure's compile-time type information is pretty limited. Functions like map have no way to specify that it only accepts one-argument functions (and of course that's not even really true, with multi-collection map calls). Likewise, apply makes everything really really complicated: consider (apply f (read-list-from-user)). Does that compile successfully? Of course it must, even though we don't know if the user will enter the right number of args for f. Thus, there has to be a runtime exception for that case; then you might as well make all arity exceptions runtime anyway, since you can't be protected from them by the compiler.

Upvotes: 7

Chiron
Chiron

Reputation: 20245

In Clojure, at compile-time phase; the data structures that are previously generated by the reader are converted to Java bytecode format. Then at Clojure runtime phase; the bytecode is executed. This means that functions are only invoked at runtime.

Of course, Macros expansion happens at compile time phase.

I think, that is why exceptions related to functions arities are caught at runtime phase.

Upvotes: 4

Related Questions