Welcome! Please see the About page for a little more info on how this works.

0 votes
in Clojure by

Same for string/last-index-of. Today I ran into a reflection warning due to the absence of these. It seems useful to add them.

1 Answer

+3 votes
by
selected by
 
Best answer

Would such a type hint even be correct, given that it can return nil?

by
The possibility of type-hinting the return value as long was considered when the function was first created in Clojure/Java, but rejected in preference to having the function return nil in some cases.  See notes from Stu Halloway on this ticket: https://clojure.atlassian.net/browse/CLJ-1449
by
Are you saying that methods in Java that have return type X never return null? In the case of primitives that is true I guess, but in general it's not. If you return nil, can something go wrong you still add the type hint?
by
This answer is just a REPL and a few seconds away:

$ clj
Clojure 1.10.1
user=> (defn foo ^long [x] (if (> x 5) (inc x) nil))
#'user/foo
user=> (foo 6)
7
user=> (foo 7)
8
user=> (foo 3)
Execution error (NullPointerException) at user/foo (REPL:1).
null
user=> (pst)
NullPointerException
    user/foo (NO_SOURCE_FILE:1)
    user/foo (NO_SOURCE_FILE:-1)
    user/eval141 (NO_SOURCE_FILE:1)
    user/eval141 (NO_SOURCE_FILE:1)
    clojure.lang.Compiler.eval (Compiler.java:7177)
    clojure.lang.Compiler.eval (Compiler.java:7132)
    clojure.core/eval (core.clj:3214)
    clojure.core/eval (core.clj:3210)
    clojure.main/repl/read-eval-print--9086/fn--9089 (main.clj:437)
    clojure.main/repl/read-eval-print--9086 (main.clj:437)
    clojure.main/repl/fn--9095 (main.clj:458)
    clojure.main/repl (main.clj:458)
nil
by
Riiight, so:

user=> (defn ^long index-of [^String s ^String substring] (let [i (.indexOf s substring )] (when (nat-int? i) i)))
#'user/index-of
user=> (index-of "foo" "f")
0
user=> (index-of "foo" "x")
Execution error (NullPointerException) at user/index-of (REPL:1).
null
...