Is it possible from a variable containing a class ...
# announcements
w
Is it possible from a variable containing a class to list the possible value if the class extends enum
s
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
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
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
@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
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
I think the signature is class<*>