Reputation: 8277
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?
Upvotes: 5
Views: 1838
Reputation: 3522
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.
Upvotes: 2