在scala注释中使用常量的最佳实践 [英] Best practice for use constants in scala annotations

查看:119
本文介绍了在scala注释中使用常量的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用tapestry 5作为我选择的Web框架。 Tapestry允许我在configure类中定义符号并将符号注入其他组件。



例如,

 
public interface SymbolConstants {
static String DEFAULT_TIMEOUT_KEY =default.timeout;
}

public class AppModule {
void contributionApplicationDefault(Configuration conf){
conf.add(SymbolConstants.DEFAULT_TIMEOUT_KEY,10);
}
}

公共类MyComponent {
@Symbol(SymbolConstants.DEFAULT_VALUE_KEY)
私有长超时;
}

定义静态常量并将其用作注释值的能力为我提供了编译时检查。



我想知道如何定义常量并将它们用作scala注释的值。如果不是,那么定义/限制我们可以为scala中的注释分配的值的最佳做法是什么。

解决方案

使用'final'关键字使编译器像在Java中一样发出它。例如,

  object Foo 
{
final val MY_SYMBOLIC_CONSTANT =whatever
}

看来,你只能在引擎盖下获得一个无法静态计算的存取方法。 / p>

I use tapestry 5 as my choice of web framework. Tapestry allows me to define symbols in the configure class and inject symbols into other components.

for example,

public interface SymbolConstants {
  static String DEFAULT_TIMEOUT_KEY = "default.timeout"; 
}

public class AppModule {
   void contributeApplicationDefault(Configuration conf) {
       conf.add(SymbolConstants.DEFAULT_TIMEOUT_KEY, "10");
   }
}

public class MyComponent {
  @Symbol(SymbolConstants.DEFAULT_VALUE_KEY)
  private long timeout;
}

The ability to define static constants and use them as annotation values gives me compile time check.

I am wondering how to define constants and use them as values of scala annotations. If not, what is the best practice to define/limit the value that we can assign to annotations in scala.

解决方案

The 'final' keyword is required to make the compiler emit it as you would do it in Java. E.g.,

object Foo
{
   final val MY_SYMBOLIC_CONSTANT="whatever"
}

It seems that, otherwise, you only get an accessor method under the hood which is not statically calculable.

这篇关于在scala注释中使用常量的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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