【问题标题】:Can you specify the return type of a method in a clojure defrecord?您可以在 clojure defrecord 中指定方法的返回类型吗?
【发布时间】:2014-04-09 06:39:28
【问题描述】:

我已经创建了一个应用程序信息接口和一个类,但是当我查看生成的类时,所有方法的返回类型都是 Object,我可以将返回类型更改为 String 吗?文档说使用 defrecord 可以进行类型提示,但没有给出示例,我能找到的唯一示例是类型提示字段和方法参数。

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

【问题讨论】:

    标签: methods types clojure


    【解决方案1】:

    查看definterface 宏。 与 defprotocol 不同,definterface 宏提供了一种为方法编写返回类型提示的方法。

    Alan Malloy 很好地解释了这一点here:

    “协议是供 Clojure 函数使用的,而不是 应该是静态类型的;接口用于消费 Java 类,需要静态类型。”

    然后你可以像这样使用它:

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

    【讨论】:

      【解决方案2】:

      您可以键入提示协议...

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

      但有人告诉我,此类型提示可能被忽略(请参阅this 后续问题)。

      【讨论】:

      • 所以你是在问别人的问题?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-27
      相关资源
      最近更新 更多