Frederik
Frederik

Reputation: 14536

Clojure deftype: how to constrain field types?

I'm trying to write a Clojure library that can be used from Java without users knowing it is written in Clojure. For this, I need my fields to have proper types:

I like that I can do this:

(deftype Point [^double x ^double y])

Which generates a class with proper types for x/y. However, this only seems to work for primitives, not for classes:

(deftype Foo [^String bar])

Generates a:

public final Object bar;

where I would expect a:

public final String bar;

Is there a way to constrain the field types? Is there another option outside of deftype/defrecord?

Upvotes: 10

Views: 877

Answers (2)

Joost Diepenmaat
Joost Diepenmaat

Reputation: 17773

From http://clojure.org/datatypes on deftype and defrecord:

fields can have type hints, and can be primitive

note that currently a type hint of a non-primitive type will not be used to constrain the field type nor the constructor arg, but will be used to optimize its use in the class method

constraining the field type and constructor arg is planned

(my emphasis)

Upvotes: 12

Adam Sznajder
Adam Sznajder

Reputation: 9206

Maybe try to do in this way: (deftype Point [#^Integer x #^Integer y])

Upvotes: 0

Related Questions