4

I have set of key-value pairs that I declare in the code, they are static values

lets say

"blah" to 10
"save" to 20

All of these are known at compile time (i.e declared static values), Now if these were stored in HashMap , map.get("somethingElse") would not throw a compile time error, even though we know for sure at compile time that the map does not have that key.

My question is there a way/some trick to get this behavior in kotlin? Basically I want compiler to error out when trying to get a key that does not exist in a set of static key-value pairs.

I am not very knowledgeable about annotations, but is this achievable using annotation processing?

Bhargav
  • 8,118
  • 6
  • 40
  • 63
  • 2
    have you considered using an enum? see: https://kotlinlang.org/docs/reference/enum-classes.html – leonardkraemer Aug 08 '19 at 06:35
  • @leonardkraemer enums are different, they have enum value as the key (which internally is nothing but int), but for a static map i would be able to use any primitive type as the key. – Bhargav Aug 08 '19 at 08:49

1 Answers1

2

Your best bet is to write a unit-test and force run the unit-test as part of the compile/build loop.

A longer way is to have enum class as key of the static map. Thus, compiler will produce an error whenever you put elements, which are not in the enum class as key to get.

Update:

You can refer to this example:

public enum MyMapKey {
    BLAR, SAVE
}

static final Map<MyMapKey, Integer> myStaticMap = new EnumMap<MyMapKey, Integer>(MyMapKey.class); // EnumMap is in java.utils
enumMap.put(MyMapKey.BLAR, 10);
enumMap.put(MyMapKey.SAVE, 20);
String value = enumMap.get(MyMapKey.BLAR);

Note: I am more familiar with Java so the above code is in Java. Yet, you can easily convert to Kotlin.

Actually, if your map is supposed to be static, why not use enum with value(s) as in this example? Here, you don't even need a separate Map as the enum itself can map the (integer) values.

Edward Aung
  • 3,014
  • 1
  • 12
  • 15
  • UT not as good as compile time error sadly :(, for enum solution could you provide a code example please? – Bhargav Aug 08 '19 at 06:39
  • 1
    enums are different, they have enum value as the key (which internally is nothing but int), but for a static map i would be able to use any primitive type as the key. – Bhargav Aug 09 '19 at 03:38
  • Since you are locking the "static" (not the Java programming static but the frozen static) map down at compile time, that means you know all the possible values of the keys. That calls for enum. – Edward Aung Aug 09 '19 at 03:52
  • yes but enum has the constraint that the key has to be the enum itself, i cant use strings or double or float, or character as the key :( – Bhargav Aug 09 '19 at 04:09