简体   繁体   中英

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")
)

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 []))

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM