Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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")
)
like image 360
Ralph Ritoch Avatar asked Mar 19 '23 22:03

Ralph Ritoch


1 Answers

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 []))
like image 186
Nicolas Modrzyk Avatar answered Mar 23 '23 01:03

Nicolas Modrzyk