Ralph Ritoch
Ralph Ritoch

Reputation: 3440

Can you specify the return type of a method in a clojure defrecord?

I've created an application-info interface and a class but when I review the generated classes the return type for all of the methods is Object, can I change the return type to String? The documentation says type hinting is possible with defrecord but doesn't give an example, the only examples I could find were for type hinting fields and method arguments.

src/com/vnetpublishing.clj

(ns com.vnetpublishing)

(defprotocol ApplicationInfo
  (author [obj])
  (author-email [obj])
  (copyright [obj])
  (app-name [obj])
  (version [obj])
)

src/Physics.clj

(ns Physics)

(defrecord info [] com.vnetpublishing.ApplicationInfo
  (author [this] "Ralph Ritoch")
  (author-email [this] "Ralph Ritoch <root@localhost>")
  (copyright [this] "Copyright \u00A9 2014 Ralph Ritoch. All rights reserved.")
  (app-name [this] "Physics")
  (version [this] "0.0.1-alpha")
)

Upvotes: 4

Views: 995

Answers (2)

Thumbnail
Thumbnail

Reputation: 13473

You can type-hint the protocol ...

(defprotocol ApplicationInfo
  (author ^String [obj])
  ; ...
  )

but I'm told that this type-hint is probably ignored (see this follow-up question).

Upvotes: 1

Nicolas Modrzyk
Nicolas Modrzyk

Reputation: 14197

Look at definterface macro. Unlike defprotocol, the definterface macro provide a way to write return type hint for methods.

Alan Malloy explain this pretty well here:

"Protocols are for consumption by Clojure functions, which aren't supposed to be statically typed; interfaces are for consumption by Java classes, which are required to be statically typed."

You can then use it like:

(definterface Test
 (^void returnsVoid [])
 (^int returnsInt [])
 (^long returnsLong [])                                                             
 (^String returnsString [])
 (^java.util.HashMap returnsJavaUtilHashMap []))

Upvotes: 6

Related Questions