Welcome! Please see the About page for a little more info on how this works.

+1 vote
in ClojureScript by

I'm mainly writing this for posterity since i figured out a workaround, but if anyone knows why this behavior happens in the first place i'd be curious...

Let's say you have a macro that returns a float:

;; src/hello_world/macros.clj

(ns hello-world.macros)

(defmacro get-float [n]
  (float n))

...and you call it in clojurescript:

;; src/hello_world/core.cljs

(ns hello-world.core
  (:require-macros [hello-world.macros :refer [get-float]]))

(js/console.log (get-float 1.5))

you'll get the following error:

clojure.lang.ExceptionInfo: failed compiling constant: 1.5; java.lang.Float is not a valid ClojureScript constant.

The workaround is to make sure the macro returns a double:

(defmacro get-float [n]
  (double n))

I know that javascript's floats are 64 bits so they match well with java's double but shouldn't a 32-bit java float be able to auto-convert safely to a js float?

1 Answer

+1 vote
by

This happens because the compiler doesn't know about java.lang.Float. There is a multi-method for emitting constants that dispatches on class. Would be trivial to add Float, probably just not added because Clojure usually only uses Double.

See https://github.com/clojure/clojurescript/blob/df1837048d01b157a04bb3dc7fedc58ee349a24a/src/main/clojure/cljs/compiler.cljc#L319

Might make sense to open a JIRA issue.

...