Assigning a default value if one doesnt exist in enum

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?

I’m not sure exactly what you mean by that. Do you mean a function that takes an argument of type Example?

fun foo(example: Example)

In that case you can use default arguments

fun foo(example: Example = Example.EXAMPLE1)

If this isn’t what you mean, can you show a code example of what your code looks like now and where you want the default value?

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.

Are you thinking of data parsing? Like, Example.valueOf("EXAMPLE5")?

In that case, you have the same options to handle this situation as in Java:

  • You could wrap it in a try { ... } catch { ... } and handle undefined/invalid values one way or the other (i.e. returning null then)

      fun parseExample(str: String): Example? {
          return try {
              Example.valueOf(str)
          } catch(e: IllegalArgumentException) {
              null
          }
    
  • You could check beforehand if the input string is EXAMPLE5 or anything other and do your custom thing.:

      fun parseExample(str: String): Example {
          return when(str) {
              "EXAMPLE5" -> Example.EXAMPLE1
              else -> Example.valueOf(str)
          }
      }
    

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:

fun catchOrDefault(default: R, block: () → R) = try { block() } catch (e: Throwable) { default }

Then I could use it like this:

catchOrDefault(Example.EXAMPLE1) { PushType.valueOf(“EXAMPLE5”) }

1 Like