Kotlin map string to enum

[Solved]-How do I create an enum from a string in Kotlin?-kotlin

Kotlin enum classes have «static» function valueOf to get enum entry by string(like Java enums). Additionally they have «static» function values to get all enum entries. Example:

enum class MyEnum < Foo, Bar, Baz >fun main(args : Array)

If you want to create an enum value from one of its parameters, instead of the name, this funny code does a pretty decent job:

inline fun , V> ((T) -> V).find(value: V): T? < return enumValues().firstOrNull < this(it) == value >> 

This can be used like this:

enum class Algorithms(val string: String) < Sha1("SHA-1"), Sha256("SHA-256"), >fun main() = println( Algorithms::string.find("SHA-256") ?: throw IllegalArgumentException("Bad algorithm string: SHA-256") ) 

Reusable Exception Safe Solution

The default solution in Kotlin will throw an exception. If you want a reliable solution that works statically for all enums, try this!

Now just call valueOf(«value») . If the type is invalid, you’ll get null and have to handle it, instead of an exception.

inline fun > valueOf(type: String): T? < return try < java.lang.Enum.valueOf(T::class.java, type) >catch (e: Exception) < null >> 

Alternatively, you can set a default value, calling valueOf(«value», MyEnum.FALLBACK) , and avoid a null response. You can extend your specific enum to have the default be automatic

inline fun > valueOf(type: String, default: T): T < return try < java.lang.Enum.valueOf(T::class.java, type) >catch (e: Exception) < default >> 

Or if you want both, make the second:

inline fun > valueOf(type: String, default: T): T = valueOf(type) ?: default 
enum class MyEnum < Foo, Bar, Baz >val value = MyEnum.values().firstOrNull // results to MyEnum.Foo 

As bashor suggested, use MyEnum.valueOf() but please have in mind that it throws an exception if value can’t be found. I recommend using:

enum class MyEnum < Foo, Bar, Baz >try < myVar = MyEnum.valueOf("Qux") >catch(e: IllegalArgumentException)
  • How do I create an enum from a string in Kotlin?
  • How to get enum value of raw type from an enum class and a string in kotlin
  • How create string array from single string in Kotlin
  • How to create new string from old string in kotlin
  • How do I create an enum from an Int in Kotlin?
  • How to create a JSONObject from String in Kotlin?
  • kotlin safe conversion from string to enum
  • How do I create a lambda expression from a Kotlin interface?
  • How to create a Map from a List with and inner list using Kotlin
  • How to create compile-time constant in Kotlin from enum?
  • How to create a list with an attribute taken from objects of a list in kotlin
  • How to create String with certain length and same value effectively in Kotlin
  • How to create an Observable from a Deferred future using Kotlin coroutines
  • How can I use a Java String method (split) directly from Kotlin source?
  • How to return a String from a Kotlin method?
  • Kotlin URL().readText(), how to convert string from return
  • How to create from parcel with Kotlin @Parcelize?
  • Firebase firestore: how to create timestamp from seconds in Kotlin for Android
  • How to write a method in Kotlin that will return a string from Firestore?
  • Kotlin — How to get time («HH:mm») from string Date
  • How to convert Java String to Enum ConverterFactory class to Kotlin
  • How to create enum of colors (int) from android resource colors.xml
  • How to get Optional from String? and String in Kotlin
  • How to create and print an array from user in Kotlin
  • How to get name from Java enum in Kotlin
  • Create a list from a string extracted from another list with Kotlin
  • how to call a function in kotlin from a String name?
  • Seperate titles from body in String or how to parse by 2 «\n» ? Kotlin
  • How to create a Java instance of the object from Kotlin data class but don’t include all fields?
  • How do I create a Gradle project that depends on the JS from a Kotlin project?
Читайте также:  Css not any class

More Query from same tag

  • org.gradle.api.UnknownDomainObjectException: KotlinJvmAndroidCompilation with name ‘debug’ not found
  • Android|Kotlin recycle view and custom adapter is creating only one row
  • LiveData Observer not Called
  • How to get data from grpc Status.details field after StatusException in Java / Kotlin?
  • onCreateOptionsMenu not being called
  • Retrieving ordered data from firebase real-time database Kotlin
  • How to implement a translate + scale animation in Jetpack Compose?
  • Can I set an object variable with a reflection value to a property of another object?
  • Android use case unit test
  • Android — Kill camera process in the background
  • onActivityResult() is not called (MapFragment)
  • Fragment not attached to the FragmentManager when loading Admob
  • How to update a value in Realtime database by adding onto the value already there
  • CalendarView Jetpack Compose Buttons Are Not Displayed
  • Kotlin Warning: Unnecessary safe call on a non-null receiver of type Marker
  • Covariant function parameter in Kotlin
  • Kotlin: Pass object in function as reference and change its instance
  • Android: How do I get clipboard data?(Can’t get clipboardmanager)
  • App getting slow after room with coroutine implementation
  • Why won’t Kotlin print the string I select from a .txt file unless it’s the last line?
  • By kotlin.. trouble with reading data from database by firebase to RecyclerView
  • onSizeChanged getting called with every recomposition
  • Kotlin input first and last name with a twist
  • I want it to vibrate when I click the button
  • None of the following functions can be called with the arguments supplied?
  • Warning updating Kotlin : File extension ‘*.klib’ was reassigned to ‘ARCHIVE’
  • Generating Kotlin method/class comments
  • how to import kotlin.js using @JsModule
  • how to convert java interface code to kotlin code?
  • What is the reason for making usage of sealed classes in when expression behave differently if when is used as an expression and not as a statement?
Читайте также:  Php div class center

Источник

How do I create an enum from a string in Kotlin?

I have an enum with some instances Foo and Bar . If I have a string «Foo» , how can I instantiate a Foo enum from that? In C# it would be Enum.Parse(. ) , is there an equivalent in Kotlin? Currently, the best I have found is to create a factory that switches on all possible strings, but that is error prone and performs poorly for large enumerations.

for new comers. read this detailed tutorial on enums in Kotlin. developine.com/enum-classes-in-kotlin-example

5 Answers 5

Kotlin enum classes have «static» function valueOf to get enum entry by string(like Java enums). Additionally they have «static» function values to get all enum entries. Example:

enum class MyEnum < Foo, Bar, Baz >fun main(args : Array)

Is it possible to override this at all? For example, if I wanted to implemented my own version that was case insensitive.

It’s impossible, AFAIK it’s impossible Java too. Introducing own method isn’t suitable for your case?

Doing my own method is fine sure, but it would just be nice to use an existing method so that users don’t need to worry about what this valueOfIgnoringCase method is, they just use valueOf like normal

@Developine this links to a 5 billionth search winner for me. You should check if you site has malware.

As bashor suggested, use MyEnum.valueOf() but please have in mind that it throws an exception if value can’t be found. I recommend using:

enum class MyEnum < Foo Bar Baz >try < myVar = MyEnum.valueOf("Qux") >catch(e: IllegalArgumentException)
enum class MyEnum < Foo, Bar, Baz >val value = MyEnum.values().firstOrNull // results to MyEnum.Foo 

Reusable Exception Safe Solution

The default solution in Kotlin will throw an exception. If you want a reliable solution that works statically for all enums, try this!

Now just call valueOf(«value») . If the type is invalid, you’ll get null and have to handle it, instead of an exception.

inline fun > valueOf(type: String): T? < return try < java.lang.Enum.valueOf(T::class.java, type) >catch (e: Exception) < null >> 

Alternatively, you can set a default value, calling valueOf(«value», MyEnum.FALLBACK) , and avoid a null response. You can extend your specific enum to have the default be automatic

inline fun > valueOf(type: String, default: T): T < return try < java.lang.Enum.valueOf(T::class.java, type) >catch (e: Exception) < default >> 

Or if you want both, make the second:

inline fun > valueOf(type: String, default: T): T = valueOf(type) ?: default 

Источник

How do I create an enum from a string in Kotlin?

I have an enum with some instances Foo and Bar . If I have a string «Foo» , how can I instantiate a Foo enum from that? In C# it would be Enum.Parse(. ) , is there an equivalent in Kotlin? Currently, the best I have found is to create a factory that switches on all possible strings, but that is error prone and performs poorly for large enumerations.

5 Answers 5

Kotlin enum classes have «static» function valueOf to get enum entry by string(like Java enums). Additionally they have «static» function values to get all enum entries. Example:

enum class MyEnum < Foo, Bar, Baz >fun main(args : Array)

Is it possible to override this at all? For example, if I wanted to implemented my own version that was case insensitive.

It’s impossible, AFAIK it’s impossible Java too. Introducing own method isn’t suitable for your case?

Doing my own method is fine sure, but it would just be nice to use an existing method so that users don’t need to worry about what this valueOfIgnoringCase method is, they just use valueOf like normal

@Developine this links to a 5 billionth search winner for me. You should check if you site has malware.

As bashor suggested, use MyEnum.valueOf() but please have in mind that it throws an exception if value can’t be found. I recommend using:

enum class MyEnum < Foo, Bar, Baz >try < myVar = MyEnum.valueOf("Qux") >catch(e: IllegalArgumentException)

enum class MyEnum < Foo, Bar, Baz >val value = MyEnum.values().firstOrNull // results to MyEnum.Foo 

Reusable Exception Safe Solution

The default solution in Kotlin will throw an exception. If you want a reliable solution that works statically for all enums, try this!

Now just call valueOf(«value») . If the type is invalid, you’ll get null and have to handle it, instead of an exception.

inline fun > valueOf(type: String): T? < return try < java.lang.Enum.valueOf(T::class.java, type) >catch (e: Exception) < null >> 

Alternatively, you can set a default value, calling valueOf(«value», MyEnum.FALLBACK) , and avoid a null response. You can extend your specific enum to have the default be automatic

inline fun > valueOf(type: String, default: T): T < return try < java.lang.Enum.valueOf(T::class.java, type) >catch (e: Exception) < default >> 

Or if you want both, make the second:

inline fun > valueOf(type: String, default: T): T = valueOf(type) ?: default 

Источник

Оцените статью