Using scala constants in constant expressions

I have constants that are made of other, smaller constants. for instance

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 them to be true constants because I use them in comments.

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

I want to

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

but in scala. Scalac does not select constants for use in annotations if it compiles them from the 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.

With this code:

 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 { } 

I get the following error in the line indexes = ...

the annotation argument must be constant; found: MyConstants.INDEXNAME

Edit: After you started with several build configurations, I think this is really a problem with scala -ide. The code really compiles when I create a project using gradle or sbt. I use the build tool for my real projects, so in the end it has some obscure markers in the IDE - annoying, but has little to do with functionality.

+2
source share
1 answer

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" } 
+3
source

Source: https://habr.com/ru/post/970251/


All Articles