I have following statements
(if "true" (println "working") (println "not working"))
result is - working
(if "false" (println "working") (println "not working"))
result is - working
Both the time result is same, How can I properly cast string to boolean in clojure.
You can create a new java Boolean object, which has a method that accepts a string. If you then use clojure's boolean function you can actually have it work in clojure.
(boolean (Boolean/valueOf "true")) ;;true
(boolean (Boolean/valueOf "false")) ;;false
If you must treat strings as booleans, read-string
is a reasonable choice. But if you know the input will be a well-formed boolean (ie, either "true" or "false"), you can just use the set #{"true"}
as a function:
(def truthy? #{"true"})
(if (truthy? x)
...)
Or, if you want to treat any string but "false" as truthy (roughly how Clojure views truthiness on anything), you can use (complement #{"false"})
:
(def truthy? (complement #{"false"}))
(if (truthy? x)
...)
If you want to do something as vile as PHP's weak-typing conversions, you'll have to write the rules yourself.
Using read-string
(if (read-string "false") (println "working") (println "not working"))
You should always think about wrapping code to do this kind of conversion into a clearly-named function. This enables you to be more descriptive in your code, and also allows you to change the implementation if needed at a later date (e.g. if you identify other strings that should also be counted as truthy).
I'd suggest something like:
(defn true-string? [s]
(= s "true"))
Applying this to your test cases:
(if (true-string? "true") (println "working") (println "not working"))
=> working
(if (true-string? "false") (println "working") (println "not working"))
=> not working
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With