non-nil-return for Java Fields

37 views
Skip to first unread message

cristian....@gmail.com

unread,
Mar 5, 2014, 3:25:23 AM3/5/14
to clojure-c...@googlegroups.com
Using non-nil-return has been really handy for Java methods that I know won't return null, but I'm having a similar issue when accessing (static) fields of classes. For example:

(ann len [String -> Integer])
(defn len [^String s]
    (.length s))

(len java.io.File/separator)

Will return an error:
Type Error (...) Type mismatch:

Expected:       java.lang.String

Actual:         (U String nil)
ExceptionInfo Type Checker: Found 1 error  clojure.core/ex-info (core.clj:4327)


Using non-nil-return doesn't seem to do anything (which makes sense since this isn't a method), but I can't seem to find an equivalent way to annotate that a field will not be nil. Is there a way to get around this?

Thanks,
Cristian

Ambrose Bonnaire-Sergeant

unread,
Mar 5, 2014, 3:34:51 AM3/5/14
to core.typed
I don't think this is implemented. http://dev.clojure.org/jira/browse/CTYP-50

For now I recommend using something like when-let-fail to cast your value.

(len (when-let-fail [f java.io.File/separator] f))

Di Xu

unread,
Mar 5, 2014, 3:43:02 AM3/5/14
to clojure-c...@googlegroups.com
Hi Cristian,

I'm not sure if typed clojure have this ability or not, but I've greped around, it seems it can't do this right now.

But you can get around this by:

(t/ann len [String -> Integer])
(defn len [^String s]
      (.length s))

(t/ann getFileSeparator [-> String])
(defn getFileSeparator []
  (let [s java.io.File/separator]
    (if s
      s
      (throw (RuntimeException. "impossible")))))

(len (getFileSeparator))

Thanks
Di Xu

cristian....@gmail.com

unread,
Mar 5, 2014, 4:42:57 AM3/5/14
to clojure-c...@googlegroups.com
Thanks for the suggestions. For my purposes, I'm going with when-let-fail since I'm only experiencing the use of static fields at the public API level. For testing, when-let-fail is simpler and I don't anticipate users of the library using core.typed.

Thanks,
Cristian
Reply all
Reply to author
Forward
0 new messages