On Mon, Jan 19, 2009 at 12:34 PM, Chouser <chou...@gmail.com> wrote: > > On Mon, Jan 19, 2009 at 11:03 AM, Michael Reid <kid.me...@gmail.com> wrote: >> >> (defn index-of [#^String s #^String substr] >> (.indexOf s substr)) >> >> Then the compiler will generate an optimized code path that directly >> invokes String.indexOf(String,String), and the other which will fall >> back to the reflective invocation. The reason that two code paths are >> needed is because Clojure is dynamically typed. > > When sufficient hints are provided for the compiler to find exactly > one matching function, only one path is produced. > > (defn get-first-char [#^String s] > (let [buf (make-array Character/TYPE 1)] > (.getChars s 0 1 buf 0) (first buf))) > > Calling this with a String works fine: > user=> (get-first-char "foo") > \f > > But using a StringBuffer, causes an exception: > user=> (get-first-char (StringBuffer. "foo")) > java.lang.ClassCastException: java.lang.StringBuffer cannot be cast to > java.lang.String (NO_SOURCE_FILE:0) > > If you remove the #^String type hint, you'll see that both String and > StringBuffer work fine. > > --Chouser
Interesting, I did not know this. But this seems to remove some flexibility in allowing for "duck" typing. For example, this prevents me from writing a class that implements a method with a signature identical to String.getChars(int,int,char[],int) and substituting that for argument to get-first-char. Of course I could remove the type hint to allow such a scenario but then I lose the direct invocation for the case when I pass in a String. I thought this would be allowed. Thanks for the clarification. /mike. --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Clojure" group. To post to this group, send email to clojure@googlegroups.com To unsubscribe from this group, send email to clojure+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~----------~----~----~----~------~----~------~--~---