https://kotlinlang.org logo
w

Wesley Acheson

10/13/2020, 4:26 PM
Is it possible from a variable containing a class to list the possible value if the class extends enum
s

Shawn

10/13/2020, 4:32 PM
just want to clarify, is
value
in this example supposed to be an instance of
Class<*>
or are you attempting to match the type of
value
in the when expression?
g

Giorgos Neokleous

10/13/2020, 4:34 PM
Yes. you can either have an exchaustive when
Copy code
when (value) {
   ...
   Enum.VALUE_ONE::class.java -> "A Enum Value 1"
   Enum.VALUE_TWO::class.java -> "A Enum Value 2"
}
or
Copy code
when (value) {
   ...
    Enum::class.java -> value.enumConstants.first { it::class.java == value }.name
}
s

Shawn

10/13/2020, 4:36 PM
if the content of
value
is
YourEnum::class.java
then I don’t believe you’ll be able to match against
Enum::class.java
but I might be misunderstanding the question
w

Wesley Acheson

10/13/2020, 4:37 PM
@Shawn I'm actually trying to catch an exception from jackson. When converting from Json it has a targetType field on InvalidFormatException. So baically I'm trying to list the possible values when someone enters a bad value. So value is the class.
Yeah you are right here. I was trying to simplify. code currently looks like this.
Copy code
val type: String = if (formatException.targetType == String::class.java) "a String"
                else if (formatException.targetType == BigDecimal::class.java) "a Number"
                else if (formatException.targetType == ZonedDateTime::class.java) "a Date"
                else if (Enum::class.java.isAssignableFrom(formatException.targetType)) "a value of type ${formatException.targetType.simpleName}"
                else formatException.targetType.simpleName
but I was hoping to change back to a
when
when I got the values nailed down. something like
Copy code
val type: String = when {
                    formatException.targetType == String::class.java -> "a String"
                    formatException.targetType == BigDecimal::class.java -> "a Number"
                    formatException.targetType == ZonedDateTime::class.java -> "a Date"
                    Enum::class.java.isAssignableFrom(formatException.targetType) -> "a value of type ${formatException.targetType.simpleName}" // Possible values here.
                    else -> formatException.targetType.simpleName
                }
s

Shawn

10/13/2020, 4:49 PM
You can definitely clean this up a bit with a
when
, but the ability to print all the possible values is entirely predicated on whether or not Jackson gives you a
Class<*>
more specific than
Class<Enum>
w

Wesley Acheson

10/13/2020, 5:21 PM
I think the signature is class<*>