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

二次信任 提交于 2019-12-07 08:55:31

问题


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

回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/22954681/can-you-specify-the-return-type-of-a-method-in-a-clojure-defrecord

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!