https://kotlinlang.org logo
#getting-started
Title
# getting-started
a

althaf

08/13/2021, 1:19 PM
Hi
Copy code
enum class Role(val letter: Char) {
    APPROVER('U'),
    ADMIN('D'),
    INQUIRER('R'),
    OPERATOR('O');
}
we have create this enum for code readability and we don't have direct control over how server is returning constants for the user roles, so they have done it this way 'U' , R etc apiRespose.role = "U" Role.valueOf(apiResponse.role) will not work ,as it is expecting  'APPROVER' as input . How can i achieve same benefit of Role.valueOf( ) wrt ot the 'letter' attribute in the enum
a

Arslan Armanuly

08/13/2021, 1:29 PM
you can make extension function that will do something like this
Copy code
Role.values().first { it.letter == 'U' }
h

hho

08/13/2021, 1:31 PM
a

Arslan Armanuly

08/13/2021, 1:34 PM
exactly
a

althaf

08/13/2021, 1:44 PM
@hho thank you
e

ephemient

08/13/2021, 2:43 PM
with this few cases it isn't faster, but if you have many then
Copy code
val rolesByLetter: Map<Char, Role> = Role.values().associateBy { it.letter }
rolesByLetter['U']
would save you from repeated linear scan
5
b

Bruno Medeiros

08/14/2021, 5:42 AM
it.letter
, isn't it?
👌 1