Skip to content

Instantly share code, notes, and snippets.

@noahlz
Last active December 19, 2015 10:49
Show Gist options
  • Save noahlz/5943779 to your computer and use it in GitHub Desktop.
Save noahlz/5943779 to your computer and use it in GitHub Desktop.
Understanding type hints for char primitives in clojure.
user=> (set! *warn-on-reflection* true)
true
user=> (defn is-letter? [c] (Character/isLetter c))
Reflection warning, NO_SOURCE_PATH:1:22 - call to isLetter can't be resolved.
#'user/is-letter?
user=> (defn is-letter? [^char c] (Character/isLetter c))
user=> CompilerException java.lang.IllegalArgumentException: Only long and double primitives are supported, compiling:(NO_SOURCE_PATH:1:1)
;; Ugh...no.
user=> (defn is-letter? [c] (let [^char c c] (Character/isLetter c)))
#'user/is-letter?
;; Note:
user=> (is-letter? "b")
ClassCastException java.lang.String cannot be cast to java.lang.Character user/is-letter? (NO_SOURCE_FILE:1)
;; More concise (probably "idiomatic")
user=> (defn is-letter? [c] (Character/isLetter (char c)))
#'user/is-letter?
;; Same classcast exception (as expected)
user=> (is-letter? "b")
ClassCastException java.lang.String cannot be cast to java.lang.Number clojure.lang.RT.charCast (RT.java:927)
;; You can avoid the use of (char) coercion, but this defeats the purpose
;; of the type hint, if you are processing a String seq.
user=> (defn is-letter? [^Character c] (Character/isLetter c))
#'user/is-letter?
;; Also, same (expected) classcast exception
user=> (is-letter? "b")
ClassCastException java.lang.String cannot be cast to java.lang.Character user/is-letter? (NO_SOURCE_FILE:1)
@noahlz
Copy link
Author

noahlz commented Jul 7, 2013

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment