如何在线程(->)宏中键入提示? [英] How can you type hint within the threading (->) macro?

查看:56
本文介绍了如何在线程(->)宏中键入提示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些Clojure代码正在尝试通过几层Java代码进行互操作(在本例中为

I have some Clojure code that is trying to interop through a couple layers of Java code (in this case, java.nio.Path by way of java.nio.file.WatchEvent<?>:

(defn unroll-event
  [^WatchEvent event]
  { :kind (.kind event)
    :context (.context event)
    :path (-> event .context .toAbsolutePath .toString)})

在此代码中,我键入了提示 event ,因此,我认为它应该能够弄清楚应该使用什么 .context .返回,这样就可以弄清楚 .toAbsolutePath .toString 的作用.我认为在这种情况下,因为

In this code, I have type hinted event, so I would think it should be able to figure out what .context is supposed to return, and as such, be able to figure out what .toAbsolutePath and .toString do. I think in this case, since .context is defined has returning a generic type T, I am wondering if I can type hint the call to .context. I've tried just prepending ^java.nio.file.Path to .context, and ^Path and ^String to .toAbsolutePath and toString, respectively, but I still get the warnings:

Reflection warning, junkcode/core.clj:28 - reference to field toAbsolutePath can't be resolved.
Reflection warning, junkcode/core.clj:28 - reference to field toString can't be resolved.

在这种情况下我可以做些什么吗?是因为-> 是宏,并且其中存在用于类型提示的特殊规则?

Is there something I can do in this case? Is it because -> is a macro and there are special rules for type hinting within that?

推荐答案

(-> x .blah ^ String .bar)基本上扩展为(^ String .bar(.blah x)),这显然不是您想要的提示所在.关键是类型提示在任何上下文(例如宏)中都没有特殊的行为:它只是应用于源代码符号的元数据.在您的示例-> 中,没有地方可以将元数据放在输入表单上,这会使它成为输出表单中所需的位置.因此,您需要编写其他形式,例如(-> ^ Path(.context event).toAbsolutePath str).

(-> x .blah ^String .bar) expands to, basically, (^String .bar (.blah x)), which is clearly not where you want the hint. The point is that type-hinting does not have special behavior in any context (eg, macros): it's just metadata applied to the source-code symbols. In your example ->, there is no place that you can put metadata on the input form that will cause it to be where you want in the output form. So you need to write some other form, like (-> ^Path (.context event) .toAbsolutePath str), for example.

此外,Clojure的推论者对泛型类型一无所知,因此方法返回T被视为方法返回对象,这解释了为什么您需要在此处进行提示.

Also, Clojure's inferencer doesn't know anything about generic types, so a method-returning-T gets treated as a method-returning-Object, which explains why you need to hint at all in here.

这篇关于如何在线程(-&gt;)宏中键入提示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆