在常量表达式中使用 scala 常量 [英] Using scala constants in constant expressions

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

问题描述

我有一些常量,它们由其他较小的常量组成.例如

I have constants, that are made of other, smaller constants. For example

object MyConstants {
    final val TABLENAME = "table_name";
    final val FIELDNAME = "field_name";
    final val INDEXNAME = TABLENAME + "_" + FIELDNAME + "_ix"; // this one does not want to be constant
}

我希望这些是真正的常量,因为我在注释中使用它们.

I want these to be true constants because I use them in annotations.

我如何使它工作?(在 Scala 2.11 上)

How do I make it work? (on scala 2.11)

我想要的是

interface MyConstants {
    String TABLENAME = "table_name";
    String FIELDNAME = "field_name";
    String INDEXNAME = TABLENAME + "_" + FIELDNAME + "_ix";
}

但在 Scala 中.如果 Scalac 从 Java 类/接口(参见SI-5333) 所以我决定把它们放在一个 Scala 对象中.它适用于文字和带有文字的表达式,但不适用于带有其他常量的表达式.

but in scala. Scalac does not pick up constants for usage in annotations if it compiles them from java class/interface (see SI-5333) so I decided to put them in a scala object. It works for literals, and for expressions with literals, but not for expressions with other constants.

使用此代码:

import javax.persistence.Entity
import javax.persistence.Table
import org.hibernate.annotations.Index

object MyConstants {
    final val TABLENAME = "table_name";
    final val FIELDNAME = "field_name";
    final val INDEXNAME = TABLENAME + "_" + FIELDNAME + "_ix";
}

@Entity
@Table(name = MyConstants.TABLENAME)
@org.hibernate.annotations.Table(
    appliesTo = MyConstants.TABLENAME,
    indexes = Array(new Index(name = MyConstants.INDEXNAME, columnNames = Array(MyConstants.FIELDNAME)))) 
class MyEntity {
}

我在 indexes = ...

注解参数需要是一个常量;找到:MyConstants.INDEXNAME

annotation argument needs to be a constant; found: MyConstants.INDEXNAME

在摆弄了一些构建配置之后,我认为这实际上是一个 Scala-ide 特定问题.当我使用 gradle 或 sbt 构建项目时,代码确实可以正常编译.我确实在我的实际项目中使用了构建工具,所以最后它是关于在 IDE 中有一些难以理解的标记 - 烦人,但与功能无关.

推荐答案

我在带有 Scala 的 JPA 中使用了常量.这段代码编译通过,我使用了它:

I used constants in JPA with scala. This code compiles, and I used it:

FreeDays.scala

@Entity
@Table(name = "free_days")
@NamedQueries(
  Array(
    new NamedQuery(name = JpaQueries.IS_FREE_DAYS, query = "SELECT f FROM FreeDays f WHERE f.dateOfFreeDay = :" + JpaQueries.DATE)
  )
)
class FreeDays {

  def this(id: Int, name: String, dateOfFreeDay: Date) = {
    this()
    this.id = id
    this.name = name
    this.dateOfFreeDay = dateOfFreeDay
  }

  @Id
  @GeneratedValue
  var id: Long = _

  var name: String = _

  @Column(name = "date_of_free_day")
  @Temporal(TemporalType.DATE)
  var dateOfFreeDay: Date = _
}

JpaQueries.scala

object JpaQueries extends JpaQueries

sealed trait JpaQueries {
  final val IS_FREE_DAYS = "IS_FREE_DAYS"
  final val DATE = "date"
}

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

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