Property references as compile-time strings


#1

When developing in Java I’ve used to writing classes to store field names as constants for use in reflection and annotations:

// common
private static final String FIELD_ID = "id";
private static final String FIELD_NAME = "name";

// user
private static final String FIELD_EMAIL = "email";

It obviously works but isn’t refactoring-friendly and leads to a mess and somewhat difficult to maintain: when adding another constant you should look up if the field is already defined, and possibly move it to the “common” section etc.

Now in Kotlin I could use property references (spring validation example):

errors.rejectValue(Entity::name.name, AppError.NAME_ALREADY_TAKEN.name)
...
errors.rejectValue(User::email.name, AppError.EMPTY_REQUIRED_FIELD.name)

But I can’t use that in annotations because such expressions aren’t constants.
Is there a solution I’m missing or maybe even better approach?
Could the feature be implemented in the language so we can reference properties/fields like User#email as a constant strings?


#2

There is an issue for that: https://youtrack.jetbrains.com/issue/KT-16304