你能在clojure defrecord中指定一个方法的返回类型吗? [英] Can you specify the return type of a method in a clojure defrecord?
问题描述
我创建了一个应用程序信息接口和类,但是当我审查生成的类的所有方法的返回类型是Object,我可以更改返回类型为String?文档说明类型提示可能与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
src/com/vnetpublishing.clj
(ns com.vnetpublishing)
(defprotocol ApplicationInfo
(author [obj])
(author-email [obj])
(copyright [obj])
(app-name [obj])
(version [obj])
)
src / Physics.clj
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")
)
推荐答案
查看 definterface 宏。
与defprotocol不同,definterface宏提供了一种为方法写入返回类型提示的方法。
Look at definterface macro. Unlike defprotocol, the definterface macro provide a way to write return type hint for methods.
Alan Malloy对此进行了很好的解释此处:
Alan Malloy explain this pretty well here:
协议是用于消费Clojure函数,不是
应该是静态类型的;接口是由
消费的Java类,需要静态类型。
"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."
您可以使用它:
(definterface Test
(^void returnsVoid [])
(^int returnsInt [])
(^long returnsLong [])
(^String returnsString [])
(^java.util.HashMap returnsJavaUtilHashMap []))
这篇关于你能在clojure defrecord中指定一个方法的返回类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!