Scala 常量表达式和计算字符串文字 [英] Scala constant expressions and computed string literals

查看:39
本文介绍了Scala 常量表达式和计算字符串文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Java 注释和它们的参数必须是常量"的规定方面遇到了一些棘手的问题.Scala 2.8 语言规范的 6.24 声明常量表达式"是以下任何一种(强调我的):

I'm running into some trickiness with Java annotations and the stipulation that their arguments must be "constants". 6.24 of the Scala 2.8 Language Specification states that "constant expressions" are any of the following (emphasis mine):

  • 值类的文字,例如整数
  • 字符串文字
  • 使用 Predef.classOf (§12.5) 构造的类
  • 来自底层平台的枚举元素
  • 一个文字数组,形式为 Array(c1, ..., cn),其中所有的 ci 都是它们自己常量表达式
  • 由常量值定义(第 4.1 节)定义的标识符.

现在,字符串文字"的定义方式似乎只是一个"或"""分隔的字符块,这是非常明确的.那么,我的问题是为什么给出

Now, a "string literal" seems to be defined in such a way that it's really just one " " or """ """ delimited block of characters, which is pretty clear-cut. My question, then, is why given

object MyObject {
  final val MY_CONSTANT1="foo"
  final val MY_CONSTANT2="bar" + "baz"
  final val MY_CONSTANT3="qux" + "quux" + "frobozz"
}

// ...

@MyAnnotation( ??? )
def Foo(): Unit {
...

@MyAnnotation 使用 MY_CONSTANT1 和 MY_CONSTANT2 而不是 MY_CONSTANT3 编译和 scaladocs(我得到注释参数需要是一个常量").为什么 MY_CONSTANT2 可以工作?是否有一些未指定的最多两个字符串文字可以组合成一个更大的规则在工作中,还是我疯了?

@MyAnnotation compiles and scaladocs with MY_CONSTANT1 and MY_CONSTANT2, but not MY_CONSTANT3 (I get "annotation argument needs to be a constant"). Why does MY_CONSTANT2 work at all? Is there some unspecified at-most-two-string-literals-can-combine-to-become-a-larger-one rule at work, or am I insane?

编辑我使用的是 Scala 2.10,它似乎修复了早期 Scala 版本中一些与注释相关的编译器错误.

edit I'm using Scala 2.10, which seems to have fixed some annotation-related compiler errors from earlier Scala versions.

推荐答案

你说它编译和 scaladocs",所以我猜你的错误是当你运行 scaladoc 时,就像我一样.

You say it "compiles and scaladocs", so I'm guessing your error is when you run scaladoc, as it was for me.

使用 scaladoc,您将获得一个只运行到 typer 阶段的专用编译器.

With scaladoc, you get a specialized compiler that only runs to the typer phase.

它在打字机中自定义的一件事是:

One of the things it customizes in its typer is:

override def canAdaptConstantTypeToLiteral = false

将其更改为 true,您的简单示例将使用 scaladoc.

Change that to true, and your trivial example will scaladoc.

adapt 开头的大注释说这是它做的第一件事,或者更确切地说,是它在 scaladocking 时不做的第零件事.

The big comment at the beginning of adapt says this is the first thing it does, or rather, the zeroth thing it doesn't do when scaladocking.

*  (0) Convert expressions with constant types to literals (unless in interactive/scaladoc mode)

只是为了好玩,我会试着翻转旗帜看看有什么坏处.(scala 文档构建良好.该标志源于演示编译器的行为,但对我来说它如何应用于 scaladoc 并不明显.)

Just for fun, I'll try flipping the flag to see what breaks. ( the scala docs build fine. The flag grew out of presentation compiler behavior, but it's not obvious to me how it applies for scaladoc.)

这篇关于Scala 常量表达式和计算字符串文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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