yegor256
yegor256

Reputation: 105043

is it possible to have type hints without LET?

This is my code (an example):

(def foo (.java_method java_object))
(debug "result of method bar() on object foo: " (.bar foo))

I get a warning (foo is of type FooType in Java):

Reflection warning, example/test.clj:2 - call to bar can't be resolved

I can remove the warning with this type hint:

(def foo (.java_method java_object))
(debug "result of method bar() on object foo: " (.bar ^FooType foo))

This works, but I have to do this type hinting every time I use foo. Another solution would be to use let, but it creates extra indentation level, which I'd like to avoid. Is it possible to do something like?:

(def foo (.java_method java_object))
(set-type foo FooType)
(debug "result of method bar() on object foo: " (.bar foo))

Upvotes: 0

Views: 142

Answers (2)

Ankur
Ankur

Reputation: 33637

You can associate type hint with def.

(def ^FooType foo (.java_method java_object))

UPDATE:

Example:

user=> (set! *warn-on-reflection* true)
true
user=> (import java.util.Hashtable)
java.util.Hashtable
user=> (def ^Hashtable table (Hashtable.))
#'user/table
user=> (.put table "one" 1)
nil
user=> (.put table "two" 2)
nil

Upvotes: 1

amalloy
amalloy

Reputation: 91837

No. For associating compile-time metadata like type-hints with named values, use let.

Upvotes: 1

Related Questions