I wanted to know if it was possible to set a default value for a enum class if a value doesn’t exist in the class.
So if a enum class looked like → enum class Example { EXAMPLE1, EXAMPLE2, EXAMPLE3, EXAMPLE4 }
and I say a value calls for Example.EXAMPLE5 is there a way I can default it to have a value of Example.EXAMPLE1?
You can’t just make a static call like Example.EXAMPLE5, because it simply won’t compile. In case of executing out-of-date Jar it will throw some kind of runtime error when parsing the bytecode.
The only sensible example I could think of would be a data parsing like with Jackson, JAXB, etc. If you want to avoid null values you could then use default values or Null Object pattern depending on your case.
I assume you mean by calling Example.valueOf(“EXAMPLE5”), you want a default value instead of it throwing an exception.
My solution for this was to first create a general kotlin function that returns a default value in case of any error: