Check the class of something in clojure?

Viewed 8207

I'm learning clojure and have a very basic question: given that clojure has type inference, how can you tell what class was inferred?

For instance, these would each result in different data types:

(2)
(/ 2 3)
(/ 2.0 3)

Is there some kind of class function that will return the data type? Also, is there a normal way of casting something to be a specific type? So in the second example above, what would I do if I wanted the result to be float?

2 Answers

There is a type function in the clojure.core library.

user> (type 2)
java.lang.Integer

user> (type (/ 2 3))
clojure.lang.Ratio

user> (type (/ 2.0 3))
java.lang.Double

If you want to convert a given number into a float then use float.

user> (float 10)
10.0

Similarly you may not need to cast because the following works:

user> (Double/toString (/ 2 3))
"0.6666666666666667"

However, this does too:

user> (str (/ 2 3))
"0.6666666666666667"
Related